Class.forName(aa).newInstance 这样加载一个实现类,如果这个实现类有多个构造函数,是否都会调用呢?

解决方案 »

  1.   

    Class.forName(aa).newInstance只会调用无参数的构造函数若没有 报异常
      

  2.   

    Just Try: 
    public class TestClassforName { public TestClassforName() {
    System.out.println("Empty Paramter");
    }

    public TestClassforName(int i) {
    System.out.println("Int Parameter");
    } /**
     * @param args
     * @throws ClassNotFoundException 
     * @throws IllegalAccessException 
     * @throws InstantiationException 
     */
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    // TODO Auto-generated method stub
    Class.forName("TestClassforName").newInstance();
    }}
    输出: Empty Paramter
    证明只会调用无参构造函数, 没有会报InstantiationException.
      

  3.   

    只会调用无参数构造函数;如果需要设置参数,可以通过set方法实现。
      

  4.   

    只会调用无参数构造函数;如果需要设置参数,可以通过set方法实现。       请问一下这个要怎么实现?
      

  5.   

    可以通过下述方法调用有参数的构造函数:
    import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;public class TestClassforName { public TestClassforName() {
    System.out.println("Empty Paramter");
    }

    public TestClassforName(int i) {
    System.out.println("Int Parameter " + i);
    } /**
     * @param args
     * @throws ClassNotFoundException 
     * @throws IllegalAccessException 
     * @throws InstantiationException 
     * @throws NoSuchMethodException 
     * @throws SecurityException 
     * @throws InvocationTargetException 
     * @throws IllegalArgumentException 
     */
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
    // TODO Auto-generated method stub
    Class c = Class.forName("TestClassforName");
    Constructor cc = c.getConstructor(int.class);
    cc.newInstance(3);
    // .newInstance();
    }}