反射小案例学习笔记
案例一
/*** ArrayList<Integer>的一個(gè)對象,在這個(gè)集合中添加一個(gè)字符串?dāng)?shù)據(jù),如何實(shí)現(xiàn)呢?* 泛型只在編譯期有效,在運(yùn)行期會(huì)被擦除掉* @throws Exception*/@Testpublic void ArrayTest() throws Exception {ArrayList<Integer> list = new ArrayList<>();list.add(111);list.add(222);Class clazz = Class.forName("java.util.ArrayList"); //獲取字節(jié)碼對象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的屬性的值設(shè)置為value。*/ public class Tool {public void setProperty(Object obj, String propertyName, Object value) throws Exception {Class clazz = obj.getClass(); //獲取字節(jié)碼對象Field f = clazz.getDeclaredField(propertyName); //暴力反射獲取字段f.setAccessible(true); //去除權(quán)限f.set(obj, value);} }/*** * A:案例演示* public void setProperty(Object obj, String propertyName, Object value){},* 此方法可將obj對象中名為propertyName的屬性的值設(shè)置為value。* @throws Exception*/@Testpublic 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);}案例三
/*** * 已知一個(gè)類,定義如下:* 包名: com.example.reflect.DemoClass;** public class DemoClass {public void run() {System.out.println("welcome to beijinf!");}}* (1) 寫一個(gè)Properties格式的配置文件,配置類的完整名稱。* (2) 寫一個(gè)程序,讀取這個(gè)Properties配置文件,獲得類的完整名稱并加載這個(gè)類,用反射的方式運(yùn)行run方法。* @throws Exception*/@Testpublic 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;}@Overridepublic 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!");} }轉(zhuǎn)載于:https://blog.51cto.com/357712148/2158308
總結(jié)
- 上一篇: 我们一般的前端开发流程
- 下一篇: webpack/gulp的z-index