Java類載入器2.反射的使用
阿新 • • 發佈:2018-12-11
反射的使用
1、通過反射機制獲取Java類的構造方法並使用
(1)Person類
package cn.itcast_01; public class Person { private String name; int age; public String address; public Person() { } private Person(String name) { this.name = name; } Person(String name, int age) { this.name = name; this.age = age; } 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; } private void function() { System.out.println("function"); } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", address=" + address + "]"; } }
(2)通過反射機制獲取Person類的無參構造方法並使用
package cn.itcast_02; import java.lang.reflect.Constructor; import cn.itcast_01.Person; /* * 通過反射獲取構造方法並使用。 */ public class ReflectDemo { public static void main(String[] args) throws Exception { // (1)獲取Java類的位元組碼檔案物件 Class c = Class.forName("cn.itcast_01.Person"); // 獲取構造方法 // public Constructor[] getConstructors():所有公共構造方法 // public Constructor[] getDeclaredConstructors():所有構造方法 // Constructor[] cons = c.getConstructors(); // Constructor[] cons = c.getDeclaredConstructors(); // for (Constructor con : cons) { // System.out.println(con); // } // (2)獲取單個構造方法 // public Constructor<T> getConstructor(Class<?>... parameterTypes) // 引數表示的是:你要獲取的構造方法的構造引數個數及資料型別的class位元組碼檔案物件 Constructor con = c.getConstructor();// 返回的是無參構造方法物件 // Person p = new Person(); // System.out.println(p); // public T newInstance(Object... initargs) // (3)使用此 Constructor 物件表示的構造方法來建立該構造方法的宣告類的新例項,並用指定的初始化引數初始化該例項。 Object obj = con.newInstance(); System.out.println(obj); // Person p = (Person)obj; // p.show(); } }
(3)通過反射機制獲取Person類的帶參構造方法並使用
package cn.itcast_02; import java.lang.reflect.Constructor; /* * 需求:通過反射去獲取該構造方法並使用:public Person(String name, int age, String address) * Person p = new Person("林青霞",27,"北京"); * System.out.println(p); */ public class ReflectDemo2 { public static void main(String[] args) throws Exception { // 獲取位元組碼檔案物件 Class c = Class.forName("cn.itcast_01.Person"); // 獲取帶參構造方法物件 // public Constructor<T> getConstructor(Class<?>... parameterTypes) Constructor con = c.getConstructor(String.class,int.class,String.class); // 通過帶參構造方法物件建立物件 // public T newInstance(Object... initargs) Object obj = con.newInstance("林青霞", 27, "北京"); System.out.println(obj); } }
2、
3、
4、
5、