1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
public class ConstructCollector {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Class<?> clazz = Class.forName("site.xixing.demo.reflect.ReflectTarget");
System.out.println("获取全部公有的构造方法"); Constructor<?>[] constructors = clazz.getConstructors(); for (Constructor<?> constructor : constructors) { System.out.println(constructor); }
System.out.println("获取全部的构造方法"); Constructor<?>[] declaredConstructors = clazz.getDeclaredConstructors(); for (Constructor<?> declaredConstructor : declaredConstructors) { System.out.println(declaredConstructor); }
System.out.println("获取单个公有构造方法"); Constructor<?> constructor = clazz.getConstructor(char.class); System.out.println(constructor);
System.out.println("获取单个私有构造方法"); Constructor<?> declaredConstructor = clazz.getDeclaredConstructor(int.class); System.out.println(declaredConstructor);
System.out.println("通过反射私有构造方法创建实例"); declaredConstructor.setAccessible(true); ReflectTarget reflectTarget=(ReflectTarget) declaredConstructor.newInstance(1); reflectTarget.sayHello();
} }
|