反射:通过配置文件去读取相关属性

利用反射,去读取配置文件里边的内容

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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值