package reflex; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class ReflectDemo02_getConstructor_public { /* * 获得class对象 就是为了获得其中的: * 1.构造方法 * 2.成员变量 * 3.成员方法 * * * 通过反射获得构造方法并使用。 */ public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { // 获取字节码文件对象 Class c = Class.forName("reflex.Person"); // 获取所有构造方法 // public Constructor[] getConstructors() // 只能获得通过public 修饰的 我有三个构造方法 // 但是剩下的那个构造并没有修饰符进行修饰 // Constructor[] cons = c.getConstructors(); // for (Constructor con : cons) { // System.out.println(con); // } /* * 获取所有构造方法:(Declare:声明) public Constructor<?>[] getDeclaredConstructors() * throws SecurityException返回 Constructor 对象的一个数组,这些对象反映此 Class 对象表示的类声明的所有构造方法。 * 它们是公共、保护、默认(包)访问和私有构造方法。 */ Constructor[] cons = c.getDeclaredConstructors(); for (Constructor con : cons) { System.out.println(con); } // 成功获得了三个,即所有的构造方法 // 即使加上了private修饰的构造方法也能够访问到 // 获取单个构造方法 /* * 可变参数类型 public Constructor<T> getConstructor(Class<?>... parameterTypes) * throws NoSuchMethodException, SecurityException 参数表示的是: * 你要获取的构造方法的构造参数及数据类型的class字节码文件对象 * 例如: * java.lang.String.class, * int.class, * java.lang.String.class */ Constructor con = c.getConstructor(); // 返回构造方法对象 Object obj = con.newInstance(); System.out.println(obj); Person p = (Person)obj; p.show(); // 输出:Person [name=null, age=0, address=null] // 以上的步骤相当于: // Person p = new Person(); // sysout p // 因为上面的构造器,得到的是Person的无参构造的对象 // 反射的好处是将来写成配置文件,上面是谁,就会运行谁 // 在我们不知道内容的情况下,极大的自主性 } }
其中的person:
package reflex; public class Person { // 成员变量 private String name; int age; public String address; // 构造方法 public Person() { } Person(String name, int age) { this.name = name; this.age = age; } private Person(String name) { this.name = name; } public Person(String name, int age, String address) { this.name = name; this.age = age; this.address = address; } // 成员方法 public void show() { System.out.println("show"); } public void method(String s) { System.out.println("method" + s); } public String getString(String s, int i) { return s + "---" + i; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", address=" + address + "]"; } private void function() { System.out.println("function"); } }