美文网首页
java反射-Constructor

java反射-Constructor

作者: 全都是泡沫啦 | 来源:发表于2018-12-03 14:17 被阅读0次

    在之前的文章java反射-Method中分析了Method的执行过程,Constructor是特殊的Method,实现原理大同小异

    1. 代码
    import java.lang.management.ManagementFactory;
    import java.lang.management.RuntimeMXBean;
    import java.lang.reflect.Constructor;
    
    public class TestProxyConstructor {
    
        private String name;
        private int age;
    
        public TestProxyConstructor(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        @Override
        public String toString() {
            return "TestProxyField{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    
        public static void main(String[] args) throws Exception {
            RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
            System.out.println("============" + runtimeMXBean.getName());
    
            Constructor<TestProxyConstructor> constructor = TestProxyConstructor.class.getConstructor(new Class[]{String.class,int.class});
            TestProxyConstructor testProxyConstructor = constructor.newInstance("hello world...",18);
            System.out.println(testProxyConstructor);
        }
    }
    执行结果
    pid=12428
    TestProxyField{name='hello world...', age=18}
    
    1. constructor.newInstance("hello world...",18);的执行如下,最后由ConstructorAccessor执行
    @CallerSensitive
        public T newInstance(Object ... initargs)
            throws InstantiationException, IllegalAccessException,
                   IllegalArgumentException, InvocationTargetException
        {
            if (!override) {
                if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                    Class<?> caller = Reflection.getCallerClass();
                    checkAccess(caller, clazz, null, modifiers);
                }
            }
            if ((clazz.getModifiers() & Modifier.ENUM) != 0)
                throw new IllegalArgumentException("Cannot reflectively create enum objects");
            ConstructorAccessor ca = constructorAccessor;   // read volatile
            if (ca == null) {
                ca = acquireConstructorAccessor();
            }
            @SuppressWarnings("unchecked")
            T inst = (T) ca.newInstance(initargs);
            return inst;
        }
    
    1. 使用工具HDFS查看生成ConstructorAccessor,反编译后如下:
    //
    // Source code recreated from a .class file by IntelliJ IDEA
    // (powered by Fernflower decompiler)
    //
    
    package sun.reflect;
    
    import java.lang.reflect.InvocationTargetException;
    
    public class GeneratedConstructorAccessor8 extends ConstructorAccessorImpl {
        public GeneratedConstructorAccessor8() {
        }
    
        public Object newInstance(Object[] var1) throws InvocationTargetException {
            TestProxyConstructor var10000;
            TestProxyConstructor var10001;
            String var10002;
            int var10003;
            try {
                var10000 = new TestProxyConstructor;
                var10001 = var10000;
                if(var1.length != 2) {
                    throw new IllegalArgumentException();
                }
    
                var10002 = (String)var1[0];
                Object var2 = var1[1];
                if(var2 instanceof Byte) {
                    var10003 = ((Byte)var2).byteValue();
                } else if(var2 instanceof Character) {
                    var10003 = ((Character)var2).charValue();
                } else if(var2 instanceof Short) {
                    var10003 = ((Short)var2).shortValue();
                } else {
                    if(!(var2 instanceof Integer)) {
                        throw new IllegalArgumentException();
                    }
    
                    var10003 = ((Integer)var2).intValue();
                }
            } catch (NullPointerException | ClassCastException var4) {
                throw new IllegalArgumentException(var4.toString());
            }
    
            try {
                var10001.<init>(var10002, var10003);
                return var10000;
            } catch (Throwable var3) {
                throw new InvocationTargetException(var3);
            }
        }
    }
    
    

    发现:其实我们平时new Object()这个操作不是原子性

    相关文章

      网友评论

          本文标题:java反射-Constructor

          本文链接:https://www.haomeiwen.com/subject/hnvhcqtx.html