反射的基本知识

读取配置文件

Properties properties = new Properties();
FileReader reader = new FileReader("src/class.txt");
properties.load(reader);
reader.close();

String methodName = properties.getProperty("methodName");
String className = properties.getProperty("className");
System.out.println(methodName);
System.out.println(className);

下面是反射的基本步骤:

Class c = Class.forName(className);
Constructor constructor = c.getConstructor();
Method method = c.getMethod(methodName,null);

Object o = constructor.newInstance();
method.invoke(o);

接下来我们写一个工具类来设置对象。

public class ReflectTool {

    public static void setProperties(Object obj,String propertyName,Object value) throws NoSuchFieldException, IllegalAccessException {
        // 根据对象获取字节码文件对象
        Class c = obj.getClass();
        // 获取该对象的propertyName成员变量
        Field field = c.getDeclaredField(propertyName);
        // 取消访问检查
        field.setAccessible(true);
        // 给对象的成员变量赋值为指定的值
        field.set(obj, value);
    }
}

测试:

class Dog{
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public Integer getAge() {
        return age;
    }
}

public class Main {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Dog dog = new Dog();
        ReflectTool.setProperties(dog,"name","哈巴狗");
        ReflectTool.setProperties(dog,"age",12);
        System.out.println(dog.getName());
        System.out.println(dog.getAge());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值