Java反射与配置文件有关的代码实例
配置文件是右键该工程,创建的File文件,文件名为properties,避免了硬编码。下面是文件的内容:
user=root
password=123456
className=com.hpe.reflect.Student
methodName=show
反射在配置文件方面的使用实例:
package com.hpe.reflect;
import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Properties;
import org.junit.Test;
public class TestOthers {
// 获取运行时类的直接父类
@Test
public void test1() {
Class<Person> clazz = Person.class;
Class<? super Person> superclass = clazz.getSuperclass();
System.out.println(superclass);
}
// 通过反射获取并运行配置文件
@Test
public void test2() throws Exception{
// 获取配置文件的对象
Properties p = new Properties();
// 获取输入流,读取配置文件,将其以流的形式读取
FileReader in = new FileReader(new File("properties"));
// 将流加载到配置文件对象中
p.load(in);
// 释放资源
in.close();
// 获取用户名和密码
String userName = p.getProperty("user");
String password = p.getProperty("password");
System.out.println("用户名" + userName + ";密码" + password);
// 通过反射获取Class对象
Class<?> clazz = Class.forName(p.getProperty("className"));
// 获取show()方法
Method method = clazz.getMethod(p.getProperty("methodName"));
Student s = (Student)clazz.newInstance();
//method.invoke(clazz.getConstructor().newInstance());
method.invoke(s);
}
// 泛型擦除:程序编译后产生的字节码文件.class是没有泛型约束的,这种现象称为泛型的擦除
@Test
public void test3() throws Exception {
ArrayList<Integer> arr = new ArrayList<>();
arr.add(123);
arr.add(456);
// 获取ArrayList字节码对象
Class<? extends ArrayList> c = arr.getClass();
// 通过反射获得add
Method method = c.getMethod("add", Object.class);
// 调用方法
method.invoke(arr, "abc");
System.out.println(arr);
}
}