java 反射

java 反射代码:

反射一个有无参构造函数的实例:

try {
	//需要实例化的类的完整路径.
	String className = "com.xt.test.Test";
	Class compositeClass = Class.forName(className);
	//newInstance创建实例, 默认调用无参构造函数.
	Test test = (Test)compositeClass.newInstance();	
} catch (Exception e) {
	e.printStackTrace();
}	

反射一个有参构造函数的实例:

try {
	String className = "com.xt.test.Test";
	Class testClass = Class.forName(className);
	Constructor ctor = testClass.getDeclaredConstructor(String.class);
	ctor.setAccessible(true);
	Test test = (Test) ctor.newInstance("AAA");
} catch (Exception e) {
	e.printStackTrace();
}

反射一个有多个参数构造函数的实例:

try {
	String className = "com.xt.test.Test";
	Class testClass = Class.forName(className);
	Class[] pType = new Class[] { int.class, String.class }; 
	Constructor ctor = testClass.getDeclaredConstructor(pType);
	ctor.setAccessible(true);
	Object obj = new Object{1, "AAA"};
	Test test = (Test) ctor.newInstance(obj);
} catch (Exception e) {
	e.printStackTrace();
}







你可能感兴趣的:(反射)