反射类&文档读写
获取类对象
1.Class.forname(String name);
name:变量
适用于配置文件读取
2.对象.getClass ();
适用于非抽象类对象
3.类.class
适用于知道类名
总结,开发一般不知道具体类名,第一种使用较多
获取成员变量 、方法、构造方法、类名
1.成员变量
类对象.getFields();============公共
类对象.getDeclaredFields();====(公共+私有+默认)
2.构造方法
类对象.getConstructors();=======有参
类对象.getDeclaredConstructors()=私有有参
类对象.getConstructor();=======无参
类对象.getDeclaredConstructor()==私有无参
3.方法
类对象,getMethods=============所有共有
类对象.getDeclaredMethods()====所有(公共+私有+默认)
4.类名
类对象.getName();
总结:除单个获取,一般获取私有修饰的,会包含公共和默认。
写入文档
1.可写对象(创建流写对象:可创建文档)
FileWriter fw = new FileWriter("d:\\Prop.txt");
2.缓存数据(集合键)
①创建集合键对象
Properties porp=new Properties();
②添加数据(集合键)
prop.put();
or
prop.setProperty();
③载入(集合键)
prop.store(fw,"GBK");
总结:此过程包含写和缓存,实例化流写(路径)及集合键对象(缓存+保存)。
读取文档
1.缓存
Properties porp=new Properties();
2.加载
prop.load(new FileReader("d:\\Prop.txt"));
调用方法
1.获取值
String calssName = prop.getProperty("calssName");
String varValue = prop.getProperty("varValueName");
String method = prop.getProperty("methodName");
2.获取类子成员
私有变量
Field field = clazz.getDeclaredField(varValue);
私有方法
Method method1 = clazz.getDeclaredMethod(method,String.class);
3.创建动态对象
Object o=类对象.newInstance();
.4.赋值+方法运行
①私有变量
获取权限
field.setAccessible(true);
赋值
field.set(o,"红楼梦");
打印
System.out.println(field.get(o));
②私有方法
获取权限
method.setAccessible(true);
执行
method.invoke();
总结
集合键负责读写,保存了数据;流对象写,创建了文档及指定了路径。