■如何獲取到.class文件字節碼對象:java
使用Class類的靜態方法forName()方法,其參數:類名前(Person)必須加上包名(reflect)ide
Class<?> personClass = Class.forName("reflect.Person");
■獲取字節碼對象的構造器分爲兩種:
this
第一種:獲取全部的構造器,只能獲取公有的構造器,而不能獲取到私有的構造器spa
Constructor<?>[] constructors = personClass.getConstructors();
第二種:獲取字節碼的指定構造器,其參數爲:傳入構造器的參數類型加上「.class」code
Constructor<?> constructor = personClass.getConstructor(String.class, int.class);
■如何使用構造器建立對象:對象
使用構造器調用newInstance(),傳入相應的參數。blog
Object p = constructor.newInstance("周娟娟", 23);
1 package reflect_constructor; 2 3 import java.lang.reflect.Constructor; 4 import java.lang.reflect.InvocationTargetException; 5 6 import reflect.Person; 7 8 public class ConstructorDemo { 9 10 public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { 11 // 使用Class獲取.class文件字節碼對象。類名前(Person)必須加上包名(reflect)。 12 Class<?> personClass = Class.forName("reflect.Person"); 13 14 // 獲取對象的全部構造器(只能獲取到公有的,不能獲取到私有構造器) 15 Constructor<?>[] constructors = personClass.getConstructors(); 16 for (Constructor<?> constructor : constructors) { 17 System.out.println(constructor); 18 } 19 20 // 使用字節碼對象獲取指定構造器 21 Constructor<?> constructor = personClass.getConstructor(String.class, int.class); 22 System.out.println(constructor); 23 24 // 使用構造器建立實例對象 25 Object p = constructor.newInstance("周娟娟", 23); 26 System.out.println(p); 27 } 28 29 }
1 package reflect; 2 3 public class Person { 4 5 private String name; 6 private int age; 7 8 public Person() { 9 } 10 11 private Person(int age) { 12 13 } 14 15 public Person(String name, int age) { 16 super(); 17 this.name = name; 18 this.age = age; 19 } 20 21 public String getName() { 22 return name; 23 } 24 25 public void setName(String name) { 26 this.name = name; 27 } 28 29 public int getAge() { 30 return age; 31 } 32 33 public void setAge(int age) { 34 this.age = age; 35 } 36 37 @Override 38 public String toString() { 39 return "Person [name=" + name + ", age=" + age + "]"; 40 } 41 42 }