元注解
public @interface 注解名称{
属性列表;
}
package com.sire.source.jdknew.annotation;
/*注解演示*/
// 定义注解
@interface MyAnno1 {
/*属性:基本数据 字符串 注解 枚举以及它们的数组*/
int intVal();
String strVal() default "sire";// 加上默认值在使用注解的时候可以不用复制
/* MyAnn anVal();
Sire enuVal();*/
int[] arrVal();
int value();
}
@interface MyAnn {}
enum Sire{
aa;
}
// 使用注解
/*@MyAnno1(intVal = 23,arrVal = 34)*/
@MyAnno1(intVal = 23,arrVal = {2,6},value= 45)
public class MyAnno {}
@Target:注解能够作用的位置。ElementType取值:TYPE:作用于类;METHOD:作用于方法;FIELD:作用于成员变量
@Retention:注解被保留的阶段。@Retention(RetentionPolicy.RUNTIME):当前描述的注解,class字节码文件会保留,并被JVM读取。
@Documented:api文档是否会抽取到注解。
@Inherited:描述注解是否被子类继承
package com.sire.source.jdknew.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/*演示元注解*/
@Target(ElementType.METHOD)
@interface Anno2{
int value();
}
/*@Anno2(23) 报错,只能允许在方法上*/
public class TestAnno2 {
@Anno2(23)
public void run(){}
}
package com.sire.source.jdknew.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/*自定义注解*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface check {
}
package com.sire.source.jdknew.annotation;
/*计算器*/
public class Calc {
@check
public void add(){
System.out.println(Integer.parseInt("a"));
System.out.println("1+0="+(1+0));
}
@check
public void sub(){
System.out.println("1-0="+(1-0));
}
@check
public void mut(){
System.out.println("1*0="+(1*0));
}@check
public void del(){
System.out.println("1/0="+(1/0));
}
}
package com.sire.source.jdknew.annotation;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;
/*测试方法*/
public class TestCalc {
public static void main(String[] args) throws Exception {
Calc c = new Calc();
// 1.获取对象
Class<Calc> clazz = (Class<Calc>) c.getClass();
// 2.获取所有方法
Method[] methods = clazz.getMethods();
int num = 0;// 异常出现次数
// 异常保存
BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));
// 3.循环所有方法
for(Method method:methods){
if(method.isAnnotationPresent(check.class)){
try {
// 4.唤醒方法
method.invoke(c);
} catch (Exception e) {
num++;
// 保存异常信息
bw.write("第"+num+"次异常");
bw.newLine();
bw.write("出现异常的方法:"+method.getName());
bw.newLine();
bw.write("异常名称:"+e.getCause().getClass().getName());
bw.newLine();
bw.write("异常信息:"+e.getCause().getMessage());
bw.newLine();
}
}
}
bw.write("---------------------------------------\n");
bw.write("总共发生了"+num+"次异常");
// 6.刷新关闭
bw.flush();
bw.close();
}
}