通过反射机制修改Class的属性值(IO+Properties)动态修改
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Properties;
public class ReflectTest08 {
public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
//创建Properties属性集合
Properties properties = new Properties();
//创建输入流
FileInputStream fileInputStream=new FileInputStream("C:\\Users\\SHIGE\\Desktop\\classinfo.properties");
//将流中的数据加载到properties对象中
properties.load(fileInputStream);
//获取类名
String className=properties.getProperty("classname");
//获取属性名
String fieldName=properties.getProperty("fieldname");
//关闭流
fileInputStream.close();
//创建class对象
Class c = Class.forName(className);
//创建class所对应的类对象
Object object=c.newInstance();
// 获取类中的一个属性对象
Field field=c.getDeclaredField(fieldName);
//打破封装
field.setAccessible(true);
//给field属性赋值
field.set(object,"施歌");
//获取filed属性值
Object fieldValue=field.get(object);
//输出
System.out.println(fieldValue);
}
}