反射小案例學習筆記
阿新 • • 發佈:2018-08-12
lan 分享 turn read ade rop arraylist println 技術 案例一
/** * ArrayList<Integer>的一個對象,在這個集合中添加一個字符串數據,如何實現呢? * 泛型只在編譯期有效,在運行期會被擦除掉 * @throws Exception */ @Test public void ArrayTest() throws Exception { ArrayList<Integer> list = new ArrayList<>(); list.add(111); list.add(222); Class clazz = Class.forName("java.util.ArrayList"); //獲取字節碼對象 Method m = clazz.getMethod("add", Object.class); //獲取add方法 m.invoke(list, "abc"); System.out.println(list); }
案例二
import java.lang.reflect.Field; /** * @author lw * @createTime 2018/8/12 11:41 * @description 此方法可將obj對象中名為propertyName的屬性的值設置為value。 */ public class Tool { public void setProperty(Object obj, String propertyName, Object value) throws Exception { Class clazz = obj.getClass(); //獲取字節碼對象 Field f = clazz.getDeclaredField(propertyName); //暴力反射獲取字段 f.setAccessible(true); //去除權限 f.set(obj, value); } } /** * * A:案例演示 * public void setProperty(Object obj, String propertyName, Object value){}, * 此方法可將obj對象中名為propertyName的屬性的值設置為value。 * @throws Exception */ @Test public void setProperty() throws Exception { Student student = new Student("您好",23); System.out.println(student); Tool t = new Tool(); t.setProperty(student,"name","美麗"); System.out.println(student); }
案例三
/** * * 已知一個類,定義如下: * 包名: com.example.reflect.DemoClass; * * public class DemoClass { public void run() { System.out.println("welcome to beijinf!"); } } * (1) 寫一個Properties格式的配置文件,配置類的完整名稱。 * (2) 寫一個程序,讀取這個Properties配置文件,獲得類的完整名稱並加載這個類,用反射的方式運行run方法。 * @throws Exception */ @Test public void Rerundome() throws Exception { BufferedReader br = new BufferedReader(new FileReader("xxx.properties")); Class clazz = Class.forName(br.readLine()); DemoClass dc = (DemoClass) clazz.newInstance(); dc.run(); }
person方法
class Student {
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
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 "Student [name=" + name + ", age=" + age + "]";
}
}
/**
* @author lw
* @createTime 2018/8/12 11:52
* @description
*/
public class DemoClass {
public void run() {
System.out.println("welcome to beijing!");
}
}
反射小案例學習筆記