呼叫執行時類的指定結構:屬性、方法、構造器
阿新 • • 發佈:2022-11-30
package day3;
import org.junit.Test;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
//呼叫執行時類的指定結構:屬性、方法、構造器
public class ReflectionDemo2 {
@Test
public void testField() throws Exception {
Class c1= Person.class;
Person p1=(Person)c1.newInstance();
//get,獲取執行時類及其父類的public的屬性
Field age = c1.getField("age");
age.set(p1,123);
System.out.println((int)age.get(p1));
//getDeclared,獲取執行時類任意許可權的屬性 Field name = c1.getDeclaredField("name"); //把非public的屬性設定為可訪問 name.setAccessible(true); name.set(p1,"Tom"); System.out.println((String)name.get(p1)); } @Test public void testMethod() throws Exception { Class c1= Person.class; Person p1=(Person)c1.newInstance(); //通過方法名和形參列表,獲取方法 Method show = c1.getDeclaredMethod("showNation", String.class); show.setAccessible(true); System.out.println((String) show.invoke(p1,"China")); //呼叫靜態方法 Method showDetail = c1.getDeclaredMethod("showDetail"); showDetail.setAccessible(true); //呼叫者為執行時類 showDetail.invoke(c1); showDetail.invoke(null); }
}
class Person {
private String name;
public int age;
public Person(){ } public Person(String name, int age) { this.name = name; this.age = age; } private Person(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "姓名:"+ name + ",年齡:" + age; } public String show(){ return this.name+" , "+this.age; } private String showNation(String nation){ return "我來自"+nation; } private static void showDetail(){ System.out.println("誰是最可愛的人"); }
}