反射方式获取构造方法并使用
Constructor<T>对象
构造器对象,属于java.base模块,java.lang.reflect包中
-
getConstructor(Class <?>... parameterType) //返回公共构造方法
-
getDeclaredConstructor(Class <?>... parameterType) //返回私有构造方法
-
getConstructors() //返回所有构造方法,但不包括私有狗杂方法
Constructor的常用方法
String getName() //返回构造方法名
T newinstance(Object... initargs) //使用此构造函数和指定参数创建并初始化对象
构造方法的使用举例
Student.java
package Demo01; import java.lang.reflect.Constructor; /** * @author :K; */ public class Student { public Student() { } public Student(String name){ System.out.println("输入的姓名为:"+name); } private Student(int age){ System.out.println("你的年龄为:"+age); } }
Reflect_GetConstructor.java
package Demo01; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class Reflect_GetConstructor { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { //1.获取Student类的字节码文件对象 //2.根据字节码文件对象,获取指定的构造器对象 //3.根据构造器对象和参数,创建对应的Student对象 Class aClass = Class.forName("Demo01.Student"); System.out.println(aClass.getName()); //获取公共的无参构造 Constructor constructor01 = aClass.getConstructor(); System.out.println(constructor01); //获得公共的有参构造 Constructor constructor02 = aClass.getConstructor(String.class); System.out.println(constructor02); //获取私有的有参构造 Constructor declaredConstructor = aClass.getDeclaredConstructor(int.class); System.out.println(declaredConstructor); //获取所有的构造方法,除去私有的构造方法 Constructor[] constructors = aClass.getConstructors(); for(Constructor constructor:constructors){ System.out.println(constructor); } System.out.println("-------------"); //构造器对象 System.out.println(constructor01); String name = constructor01.getName(); //构造器的名字 System.out.println(name); //根据构造器对象和参数,创建对应的Student对象 Student stu = (Student) constructor02.newInstance("李白"); //打印输出结果 System.out.println(stu); } }