zoukankan      html  css  js  c++  java
  • Java中2+2==5解读

    先来看一段程序,如下:

    package basic;
    
    import java.lang.reflect.Field;
    
    public class TestField {
    
        public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
            @SuppressWarnings("rawtypes")
            Class cache = Integer.class.getDeclaredClasses()[0];
            Field myCache = cache.getDeclaredField("cache");
            myCache.setAccessible(true);
            Integer[] newCache = (Integer[]) myCache.get(cache);
            newCache[132] = newCache[133];
            int a = 2;
            int b = a + a;
            System.out.printf("%d + %d = %d", a, a, b);
        }
    }

    程序正常运行,输出如下结果:

    2 + 2 = 5

    分析:

    package basic;
    
    /**
     * 类TestDeclaredClass.java的实现描述:getDeclaredClasses() 方法返回一个Class对象,包括公共,保护,默认(包)访问的私有类和类中声明的接口的数组,但不包括继承的类和接口。
     * 如果类没有声明的类或接口的成员,或者如果此Class对象表示一个基本类型,此方法返回一个长度为0的数组。
     * 
     * @author 2016年6月16日 上午10:17:51
     */
    public class TestDeclaredClass {
    
        public static void main(String[] args) {
            try {
                Class cls = TestDeclaredClass.class;
                Class[] clss = cls.getDeclaredClasses();
                for (int i = 0; i < clss.length; i++) {
                    System.out.printf("CLASS = %s 
    ", clss[i].getName());
    
                }
            } catch (SecurityException e) {
                e.printStackTrace();
            }
        }
    
        public class InnerClass1 {
    
            public InnerClass1(){
                System.out.println("InnerClass1");
            }
        }
    
        public interface Inner {
        }
    
        public class InnerClass2 {
    
            public InnerClass2(){
                System.out.println("InnerClass2");
            }
        }
    
        private class InnerPrivateClass {
    
            public InnerPrivateClass(){
                System.out.println("InnerPrivateClass");
            }
        }
    }
    
    class MyTestDeclaredClass extends TestDeclaredClass {
    }

    程序正常运行,输出如下结果:

    CLASS = basic.TestDeclaredClass$Inner 
    CLASS = basic.TestDeclaredClass$InnerClass1 
    CLASS = basic.TestDeclaredClass$InnerClass2 
    CLASS = basic.TestDeclaredClass$InnerPrivateClass 

    接着再看:

    package basic;
    
    import java.lang.reflect.Field;
    
    /**
     * 类TestGetDeclaredField.java的实现描述:getDeclaredField() 方法返回一个Field对象,它反映此Class对象所表示的类或接口的指定已声明字段。
     * name参数是一个字符串,指定所需字段的简单名称。
     * 
     * @author 2016年6月16日 上午10:36:21
     */
    public class TestGetDeclaredField {
    
        Long size;
    
        public TestGetDeclaredField(Long size){
            super();
            this.size = size;
        }
    
        public static void main(String[] args) {
            try {
                Class cls = TestGetDeclaredField.class;
                Field field = cls.getDeclaredField("size");
                System.out.println("Field = " + field.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    程序正常运行,输出如下结果:

    Field = java.lang.Long basic.TestGetDeclaredField.size

    在Java的反射中Field类和Method类的说明:要想使用反射,首先需要获得类对象所对应的Class类的类对象。一个Field对象对应的是一个反射类的属性(成员变量)信息。Field类中定义了一些方法,可以用来查询字段的类型以及设置或读取字段的值。Method类使得我们可以获得方法声明的完整信息。

    基于以上信息分析代码如下:

    Class cache = Integer.class.getDeclaredClasses()[0];
    Field myCache = cache.getDeclaredField("cache");

    获取到内部类和内部类中成员变量名为cache的属性信息。

    java.lang.Integer$IntegerCache
    static final java.lang.Integer[] java.lang.Integer$IntegerCache.cache

    我们来看JDK中关于Integer内部类IntegerCache中属性cache的源码如下:

        /**
         * Cache to support the object identity semantics of autoboxing for values between
         * -128 and 127 (inclusive) as required by JLS.
         *
         * The cache is initialized on first usage.  The size of the cache
         * may be controlled by the -XX:AutoBoxCacheMax=<size> option.
         * During VM initialization, java.lang.Integer.IntegerCache.high property
         * may be set and saved in the private system properties in the
         * sun.misc.VM class.
         */
    
        private static class IntegerCache {
            static final int low = -128;
            static final int high;
            static final Integer cache[];
    
            static {
                // high value may be configured by property
                int h = 127;
                String integerCacheHighPropValue =
                    sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
                if (integerCacheHighPropValue != null) {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                }
                high = h;
    
                cache = new Integer[(high - low) + 1];
                int j = low;
                for(int k = 0; k < cache.length; k++)
                    cache[k] = new Integer(j++);
            }
    
            private IntegerCache() {}
        }

    JavaInteger对-127到128的整形数据是有缓存的,你这里通过反射缓存中的第133号数据(既整数5)赋值给了第132号数据(既整数4),所以4就会变成5来表示。在使用int数据计算时结果是正常的,但是在打印时由于做了装箱,int数据变成了Integer,这时会采用缓存,所以4就会打印出5来。

    1、易百教程:http://www.yiibai.com/html/java/

    2、Java机智的让1+1的结果变成3:http://www.tuicool.com/articles/nIzQJjb

    3、segmentfault问题地址:https://segmentfault.com/q/1010000005732476

  • 相关阅读:
    selenium 18种元素定位方法
    python3+selenium配置可能报错记录
    adb+monkey压力测试入门
    appscan使用教程(全)
    appium---android元素定位
    QTP自动化测试
    postman Could not get any response。
    Jmeter接口测试+压力测试
    Android 偏门xml属性
    CrashHandler
  • 原文地址:https://www.cnblogs.com/RunForLove/p/5590409.html
Copyright © 2011-2022 走看看