Constructor类是java反射中重要的类,它是对类中构造器的描述的类。类似于Method(对类中方法的描述的类),Field(对类中属性的描述的类)。
通过创建Constructor的对象实例,我们可以创建源对象。
小测试demo:
package com.wtd; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.ListIterator; class Car{ public void run(){ System.out.println("----running"); } public Car() { // TODO Auto-generated constructor stub System.out.println("Car()"); } public Car(int i){ System.out.println("Car(i)"); } } public class Temp1 { public static void main(String[] args) { Class<Car> clazz = Car.class; try { Constructor<Car> constructor = clazz.getConstructor(); Car car = constructor.newInstance(); Constructor<Car> constructor2= clazz.getConstructor(int.class); Car car2 = constructor2.newInstance(2); car.run(); car2.run(); } 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(); } } }
output:
Car()
Car(i)
----running
----running
注意:
Car的构造器,必须显示声明。不然Constructor.newInstance()报错。
你的能量超乎你想象_________