黑马程序员技术交流社区
标题:
【广州校区】反射学习笔记
[打印本页]
作者:
yuhaohong
时间:
2018-1-3 11:38
标题:
【广州校区】反射学习笔记
Day17-junit、反射、Properties
1.Junit(单元测试框架)
Junit是第三方工具,取代main方法(不用每次测试都写一个新建文件和main方法)
java开发工具一包都集成了Junit的jar包
右键项目-->Build Path-->Add libraries-->Junit-->OK
@Test
public void test() {
System.out.println("测试Junit");
}
修饰符必须是 public,可以用 final 修饰,不能有返回值(void)
右键--->Run as Junit
@Before:每次执行@Test前执行一次
@Test:测试方法
@After:每次@Test执行后执行
2.反射
类的加载过程:Demo.class(纯文本文件)--->通过类加载器加载--->Demo.class(Class对象)--->实例化对象
从纯文本到Class对象,不能直接操作纯文本
反射就是直接操作Class对象的过程
类名.class
对象.getClass()
Class.forName("类全路径名")
通过反射操作构造方法、成员变量、成员方法和Class自己的信息
getName(),getSimpleName()等关于自己的信息
字符串操作
getConstructor ()、getDeclaredConstructor()
newInstance():创建对象
getField(.....)、getDeclaredField()
成员属性处理
setXxx(对象,需要设置的值...)
getMethod(.....)、getDeclareMethod()
invoke(传入对象,参数...):调用方法
如果是静态方法,对象传入null
Declare可以获得私有的,但是私有的成员使用前要调用它setAccessible(true)取出权限
通过反射擦除泛型约束
3.Properties
HashTable的子类(Map + IO)
Properties用于读取配置文件(IO)然后放到集合里(Map)
Properties的键值对一定要是String类型,文件后缀名一定是.properties
可以使用注释 #,以#开头
使用步骤:
创建对象:Properties prop = new Properties();
读取配置:prop.load(InputStream)--->把文件的数据读取放入到map集合中
获取数据:prop.getProperty("key")--->从map集合中获取数据
如果没有这个键--->return null ---> 或者可以设置默认值
prop.getProperty("key", default value)
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
FileInputStream fis = new FileInputStream("fileName.properties");
prop.load(fis);
String value = prop.getProperty("key名称");
System.out.println(value);
}
持久话数据到文件
文件格式为:key=value
store(OutputStream os, "注释"):持久化
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
prop.setProperty("key1", "value1");
prop.setProperty("key2", "value2");
prop.store(new FileOutputStream("store.properties"), "My title");
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2