案例一
/** * 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!"); }}