题目:现在有一个学生类Student,通过读取配置文件的方式。来创建这个学生类的对象,并且给属性赋值Student{id=10001, name=’zhangsan’, age=20};
package com.zd.reflex;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Properties;
public class Test {
public static void main(String[] args) throws Exception{
//获取资源类的路径(这种方式获取的路径,扩展性强,任何系统都可以使用符合OCP原则)
String path = Thread.currentThread().getContextClassLoader()
.getResource("com/zd/reflex/resources.properties").getPath();
//通过输入流读取到内存
InputStream inputStream = new FileInputStream(path);
//初始化Properties
Properties properties = new Properties();
//加载inputStream流
properties.load(inputStream);
//获取类的路径
String studentPath = properties.getProperty("studentPath");
//获取id的值
int id = Integer.valueOf(properties.getProperty("id"));
//获取name的值
String name = properties.getProperty("name");
//获取age的值
int age = Integer.valueOf(properties.getProperty("age"));
//通过反射来创建类和设置属性值
Class aClass = Class.forName(studentPath);
Object obj = aClass.newInstance();
Field idField = aClass.getDeclaredField("id");
idField.setAccessible(true);
idField.set(obj,id);
Field nameField = aClass.getDeclaredField("name");
nameField.setAccessible(true);
nameField.set(obj,name);
Field ageField = aClass.getDeclaredField("age");
ageField.setAccessible(true);
ageField.set(obj,age);
System.out.println((Student)obj);
inputStream.close();
}
}
运行结果如下图:
这是我对这道面试题的答案,如果有更好的答案,希望大神指教。