Java Class.newInstance()方法

只有当类具有默认的构造器时,才能调用Class.newInstance();否则抛异常:具体执行情况可以调试进去看看。

————————————————————————————————————————

at java.lang.Class.newInstance0(Class.java:340)

at java.lang.Class.newInstance(Class.java:308)

———————————————————————————————————————— 

 下面是关键代码调用:

public T newInstance() throws InstantiationException, IllegalAccessException

 {
        if (System.getSecurityManager() != null) {  
           checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
        }
        return newInstance0();
 }
private T newInstance0()  throws InstantiationException, IllegalAccessException 

{

       ............

       try {

                Class[] empty = {};

                final Constructor<T> c = getConstructor0(empty, Member.DECLARED); 

                ................ 

       }catch (NoSuchMethodException e) {

                throw new InstantiationException(getName());

       } 

private Constructor<T> getConstructor0(Class[] parameterTypes,  int which) throws NoSuchMethodException
 {
        Constructor[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
        for (int i = 0; i < constructors.length; i++) {
            if (arrayContentsEq(parameterTypes,  constructors[i].getParameterTypes())) {
                return getReflectionFactory().copyConstructor(constructors[i]);
            }
        }
        throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes));

 } 

原文地址:https://www.cnblogs.com/xinglongbing/p/1999305.html