利用反射,去读取配置文件里边的内容
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Properties;
public class EmpReflect {
public static void main(String[] args) throws Exception {
//1.利用反射获取实体类
Class<?> empClass = Class.forName("com.shy.reflect.Employee");
//2.通过类加载,读取emp.properties文件
InputStream is = EmpReflect.class.getClassLoader().getResourceAsStream("emp.properties");
Properties properties = new Properties();
properties.load(is);//读取IO流
//3.获取实体类的无参构造方法
Object o = empClass.getDeclaredConstructor().newInstance();
//4.获取实体类中所有的属性
Field[] fields = empClass.getDeclaredFields();
for (Field field : fields) {
//4.1获取属性名
String empName = field.getName();
//4.2获取属性修饰的参数
Class<?> type = field.getType();
//4.3设置set方法
//setId-->这种是set方法的格式,需要按照这样的格式去进行修改
String setMethods = "set"+empName.substring(0,1).toUpperCase()+empName.substring(1);
//4.4根据对应的属性名去配置文件中获取对应的值
String property = properties.getProperty(empName);
//4.5对实体类中set方法付进行赋值
Method method = empClass.getMethod(setMethods, type);
//4.6判断类型,然后进行赋值
if(type == Integer.class){
//说明这个类型是Integer类型的,需要进行强制转换
Integer integer = Integer.valueOf(property);
//4.6.1对该方法进行赋值
method.invoke(o,integer);
}else if(type == String.class){
method.invoke(o,property);
}else{
//如果需要其他类型,可以继续else if 进行添加。
throw new RuntimeException("现在暂不支持其他类型");
}
}
//直接打印
System.out.println(o);
}
}