1.
package com.xinhua.javaReflect;
public class PrivateConstruct {
private PrivateConstruct() {
System.out.println("无参构造方法被调用");
}
private PrivateConstruct(int a, int b) {
System.out.println("a = " + a + " b = " + b);
}
}
2.
package com.xinhua.javaReflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class TestPrivateConstruct {
public static void main(String[] args) {
TestPrivateConstruct testConstructor = new TestPrivateConstruct();
testConstructor.newInstanceByConstructor();
}
//通过Constructor.newInstance()创建新的类实例
private void newInstanceByConstructor() {
try {
Class c = Class.forName("com.xinhua.javaReflect.PrivateConstruct");
// 调用类PrivateConstruct的无参构造方法
Constructor c0 = c.getDeclaredConstructor();
c0.setAccessible(true);
PrivateConstruct a0 = (PrivateConstruct) c0.newInstance();
// 注意此处使用参数数组的形式,即PrivateConstruct类的有参构造方法的参数为:int a, int b,此处需要使用数组
Constructor c1 = c.getDeclaredConstructor(new Class[] {int.class, int.class});
c1.setAccessible(true);
PrivateConstruct a1 = (PrivateConstruct) c1.newInstance(new Object[] {5, 6});
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}