下面的代码是已知配置文件里面的内容,将里面的值给拿出来设置给实体类的有参构造函数。
package chapte2;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Properties;
public class chapte2 {
public static void main(String[] args) throws Exception {
Properties properties=new Properties();
ClassLoader classLoader=chapte2.class.getClassLoader(); //getClassLoader()这个是获取根路径下的,如果不是src下,得记得加上包名
InputStream inputStream=classLoader.getResourceAsStream("chapte2/aplication.properties");
properties.load(inputStream);
Class c=Class.forName(properties.getProperty("classname"));
Object o=c.newInstance(); //通过properties.getProperty获取的值就是String类型,所以并不能在实体类里面有int类型
properties.forEach((key,val)->{
if (!key.toString().equals("classname")) {
try {
Field field=c.getDeclaredField(key.toString());
field.setAccessible(true);
field.set(o,val);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
});
System.out.println(o.toString());
}
}
classname=chapte2.Myname
name=lijie
age=19
package chapte2;
public class Myname {
private String name;
private String age;
@Override
public String toString() {
return "Myname{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}
public Myname() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Myname(String name, String age) {
this.name = name;
this.age = age;
}
}
效果图如下所示
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210522161143536.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ0NzcyNDE0,size_16,color_FFFFFF,t_70)