通过传统的方式创建对象
A a = new A();
通过反射的方式创建对象
String className = “包名.A”;
类对象
Class pclass = Class.forName(className);
构造器
Constructor c = pClass.getConstructor();
通过构造器实例化
A a = (A)c.newInstance();
应用 通过配置文件获取对象
在这个文件 a.config 中保存类的全称
在这里插入代码片
配置文件中只有一行文字,内容为Hero类的路径。
直接使用Class.forName(className).newInstance()
与
Class pclass = Class.forName(className);
Constructor c = pClass.getConstructor();
Class.forName(className).newInstance()
效果一样
//一个标准的调用
public class Test {
public static void main(String[] args) {
File file = new File("src/hero.config");
String className = Test.getClassName(file);
try {
Hero hero = (Hero) Class.forName(className).newInstance();
hero.setName("rg");
System.out.println(hero);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String getClassName(File file) {
String className = null;
try (FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr)) {
className = br.readLine();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return className;
}
}
通过反射来修改属性
import ABC.A
public class TestReflection{
public static void main(String[] args){
A a = new A();
//使用传统方式修改name的值为b
a.name = "b";
try{
//获取类A的名字叫做name的字段
Field f = a.getClass().getDeclaredField("name");
//修改这个字段的值
f.set(a,"b");
}catch(Exception e){
e.printStackTrace();
}
}
}
}
强调:
getField和getDeclaredField的区别
这两个方法都是用于获取字段
getField 只能获取public的,包括从父类继承来的字段。
getDeclaredField 可以获取本类所有的字段,包括private的,但是不能获取继承来的字段。 (注: 这里只能获取到private的字段,但并不能访问该private字段的值,除非加上setAccessible(true))
用法
A a1 = new A();
//获得A类中所有定义的属性
Field[] fields = a1.getClass().getDeclaredFields();
//对所有属性设置访问权限 当类中的成员变量为private时 必须设置此项
AccessibleObject.setAccessible(fields, true);
本文探讨了Java中的反射机制,通过对比传统与反射方式创建对象,展示了如何利用反射根据配置文件获取对象。同时,文章强调了getField与getDeclaredField的区别,前者获取公共字段(包括父类),后者获取本类所有字段(包括私有),并指出在访问私有字段时的注意事项。
731





