-
获取一个类里面所有的信息,获取到了之后,再执行其他的业务逻辑 -
结合配置文件,动态的创建对象并调用方法
练习1:
public class MyTest {
public static void main(String[] args) throws IllegalAccessException, IOException {
Student s = new Student("小A", 23, '女', 167.5, "睡觉");
Teacher t = new Teacher("播妞", 10000);
//调用方法
upload(t);
}
private static void upload(Object obj) throws IllegalAccessException, IOException {
//1创建字节码文件
Class<?> clazz = obj.getClass();
//2.创建io流
BufferedWriter bw = new BufferedWriter(new FileWriter("..\\reflect\\a.txt"));
//获取所有成员变量
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
//暴力反射:因为成员变量有可能是私有化
field.setAccessible(true);
//获取变量名
String name = field.getName();
//获取变量在对象中记录的值
Object value = field.get(obj);
//写入文件
bw.write(name + "=" + value);
bw.newLine();
}
bw.close();
}
}
练习二:
//Student
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public void study(){
System.out.println("学生在学习!");
}
//set、get、toString
}
//Teacher
public class Teacher {
private String name;
private double salary;
public Teacher() {
}
public Teacher(String name, double salary) {
this.name = name;
this.salary = salary;
}
public void teach(){
System.out.println("老师在教书!");
}
// set、get、toString
}
//main
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
//1.获取properties文件内的数据
Properties prop = new Properties();
FileInputStream fis=new FileInputStream("..\\reflect\\Info.properties");
prop.load(fis);
fis.close();
System.out.println(prop);//{method=study, className=reflectDemo.Student}
//根据键获取值
String className = (String) prop.get("className");
String methodName = (String)prop.get("method");
//根据全类名获取class文件对象
Class<?> clazz = Class.forName(className);
//反射获取构造方法,创建一个对象o
Constructor<?> constructor = clazz.getDeclaredConstructor();
Object o = constructor.newInstance();
//反射获取方法,参数是方法名
Method method = clazz.getDeclaredMethod(methodName);
//因为不知道方法是不是私有化,所以暴力反射
method.setAccessible(true);
//传入对象运行当前方法
method.invoke(o);//学生在学习!
}
}
准备一个info.properties文件,以键值对的形式存储
以后若要运行其他类里面的方法,在文件内修改数据即可
将文件修改为如下,再次运行
文章来源:https://www.toymoban.com/news/detail-825557.html
总结:
文章来源地址https://www.toymoban.com/news/detail-825557.html
到了这里,关于反射的作用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!