1 import net.dsmxx.PersonFk; 2 3 import java.lang.reflect.Constructor; 4 import java.lang.reflect.InvocationTargetException; 5 6 /** 7 * Created with IDEA 8 * author:foreign 9 * Date:2019/9/29 10 * Time:20:02 11 */ 12 public class ReflectionFk { 13 public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { 14 Class clazz = PersonFk.class; 15 //1 获取public的构造方法 16 Constructor[] constructors = clazz.getConstructors(); 17 for (Constructor constructor : constructors) { 18 System.out.println("public的构造方法:" + constructor); 19 } 20 //2 根据参数获取构造方法 21 Constructor constructor = clazz.getConstructor(new Class[]{String.class, Integer.class, Boolean.class}); 22 System.out.println("String类型的构造方法:" + constructor); 23 //3 构造方法参数 24 Class[] parameterTypes = constructor.getParameterTypes(); 25 for (Class para : parameterTypes) { 26 System.out.println("构造方法参数:" + para); 27 } 28 //利用构造方法对象实例化一个类 29 Constructor constructor1 = clazz.getConstructor(new Class[]{String.class, Integer.class, Boolean.class}); 30 Object o = constructor1.newInstance("foreign", 27, true); 31 System.out.println("对象:" + o); 32 PersonFk personFk = (PersonFk) o; 33 System.out.println("对象name:" + personFk.getName()); 34 System.out.println("对象name:" + personFk.getAge()); 35 System.out.println("对象name:" + personFk.getGender()); 36 } 37 }