/**
* 通过反射运行配置文件内容
*
* 更改类或者方法只需要在txt文件中更改,不需要在源码修改
*
*/
//加载键值对数据
Properties p=new Properties();
//(txt内容为:className=com.day_1.Student;methodName=study)
p.load(new FileInputStream(new File("t.txt")));
//获取键值
String v1 = p.getProperty("className");
String v2 = p.getProperty("methodName");
//反射
Class<?> c = Class.forName(v1);
Constructor<?> constructor = c.getConstructor();
Object o = constructor.newInstance();
Method m1 = c.getDeclaredMethod(v2);
m1.invoke(o);
/**
* 通过反射绕过反省检查约束
*
*/
ArrayList<Integer> al=new ArrayList<Integer>();
al.add(18);
al.add(90);
al.add(79);
System.out.println(al);
Class c = al.getClass();
Method m = c.getMethod("add", Object.class);
m.invoke(al,"qwer");
System.out.println(al);
/**
* 通过反射写一个通用的
* 设置某个对象属性为指定的值
*
*方法:(可以作为方法,也可以封装成一个工具类)
*/
public static void setProperty(Object o,String propertyname,Object value) throws Exception{
Class<?> c = o.getClass();
Field f = c.getDeclaredField(propertyname);
f.setAccessible(true);
f.set(o,value);
}
学习过程12(反射)
最新推荐文章于 2023-12-15 17:05:31 发布