通过注解和反射配置文件
- getAnnotation(MyAnno.class) 获取到MyAnno的实现类,返回一个MyAnno类型的子类。
- Class clazz = TestPerson.class; 获取那个类的字节码文件,类就是字节码的泛型。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyAnno {
String className();
String methodName();
}
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
@MyAnno(className = "test3.Person",methodName = "speak")
public class TestPerson {
public static void main(String[] args) throws Exception{
Class<TestPerson> clazz = TestPerson.class;
MyAnno anno1 = clazz.getAnnotation(MyAnno.class);
String className = anno1.className();
String methodName = anno1.methodName();
Class clazz1 = Person.class;
Object o = clazz1.newInstance();
Method method = clazz1.getDeclaredMethod("speak");
method.setAccessible(true);
method.invoke(o);
}
}
通过注解和反射做一个简单的框架
- e.getCause() 返回的是Throw类型的子类
- e.getCause().getClass().getName()获取的是这个异常的名字
- e.getCause().getMessage() 异常的描述信息
public class Calculator {
@Check
public int add(){
return 1+0;
}
@Check
public int sub(){
return 1-0;
}
@Check
public int div(){
return 1/0;
}
@Check
public int mul(){
return 1*0;
}
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Check {
}
public class TestCheck {
public static void main(String[] args) throws Exception{
int number = 0;
BufferedWriter bw = new BufferedWriter(new FileWriter("day16/bug.txt"));
Calculator calculator = new Calculator();
Class clazz = Calculator.class;
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
if(method.isAnnotationPresent(Check.class)){
try{
method.invoke(calculator);
}catch (Exception e){
number++;
bw.write(method.getName()+"方法出错了");
bw.newLine();
bw.write("异常的名称:"+e.getCause().getClass().getName());
bw.newLine();
bw.write("异常的原因:"+e.getCause().getMessage());
bw.newLine();
bw.write("------------------------------------------");
bw.newLine();
}
}
}
bw.write("出错的异常有"+number+"个");
bw.close();
}
}
反射中泛型的擦除
public class Test {
public static void main(String[] args) throws Exception{
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
Class clazz = ArrayList.class;
Method method = clazz.getDeclaredMethod("add",Object.class);
method.setAccessible(true);
method.invoke(list,"你好");
System.out.println(list);
}
}