反射¶
概念¶
反射机制将类的各个组成部分封装为其他对象。
优点¶
- 可以在程序运行过程中,操作这些对象
- 可以解耦,提高程序的可扩展性
举例¶
Class personClass = Person.class;
Field[] fields = personClass.getFields();
for (Field field : fields) {
System.out.println(field);
}
System.out.println("===============");
Field[] declaredFields = personClass.getDeclaredFields();
for (Field declaredField : declaredFields) {
System.out.println(declaredFields);
}
Class对象的功能¶
获取功能¶
- 成员变量
Field[] getFields();
Field getField(String name);
Field[] getDeclaredFields(); // 不考虑修饰符
Field getDeclaredField(String name);
- 构造方法
Constructor<?>[] getConstructors();
Constructor<T> getConstructor(类<?>... parameterTypes);
Constructor<T> getDeclaredConstructor(类<?>... parameterTypes);
Constructor<?>[] getDeclaredConstructors();
- 成员方法
Method[] getMethods();
Method getMethod(String name, 类<?>... parameterTypes);
Method[] getDeclaredMethods();
Method getDeclaredMethod(String name, 类<?>... parameterTypes);
- 类名
String getName();
Field成员变量¶
- 设置值
void set(Object obj, Object value);
- 获取值
get(Object obj);
- 忽略访问权限
setAccessible(true);
举例¶
public class TestCheck {
public static void main(String[] args) {
Calculator calculator = new Calculator();
Class class = calculator.getClass();
Method[] methods = class.getMethods();
int errNum = 0;
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("bug.txt"));
for (Method method : methods) {
if (method.isAnnotationPresent(Check.class)) {
try {
method.invoke(calculator);
} catch (Exception e) {
errNum++;
bufferedWriter.write(method.getName() + " 方法出现异常了");
bufferedWriter.newLine();
bufferedWriter.write("异常的名称:" + e.getCause().getClass().getSimpleName());
bufferedWriter.newLine();
bufferedWriter.write("异常的原因:" + e.getCause().getMessage());
bufferedWriter.newLine();
bufferedWriter.write("-----------");
}
}
}
bufferedWriter.write("本次测试一共出现" + errNum + "次异常");
bufferedWriter.flush();
bufferedWriter.close();
}
}
public class Calculator {
@Check
public void add() {
System.out.println("1 + 0 = " + ( 1 + 0));
}
@Check
public void sub() {
System.out.println("1 - 0 = " + (1 - 0));
}
@Check
public void mul() {
System.out.println("1 * 0 = " + (1 * 0));
}
@Check
public void div() {
System.out.println("1 / 0 = " + (1 / 0));
}
public void show() {
System.out.println("此方法不被测试");
}
}