读取配置文件

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());
    }
}