@Override:用在方法之上,用来告诉别人这一个方法是改写父类的
@Deprecated:建议别人不要使用旧的API的时候用的,编译的时候会用产生警告信息,可以设定在程序里的所有的元素上.
@SuppressWarnings:暂时把一些警告信息消息关闭
设计一个自己的Annotation
只有一个参数的Annotation实现
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation1 {
String value();
}
有两个参数的Annotation实现
package chb.test.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation2 {
String description();
boolean isAnnotation();
}
Annotation实验类
@MyAnnotation1("this is annotation1")
public class AnnotationDemo {
@MyAnnotation2(description="this is annotation2",isAnnotation=true)
public void sayHello(){
System.out.println("hello world!");
}
}
Annotation测试说明类
import java.lang.reflect.Method;
import org.junit.Test;
public class TestAnnotation {
@Test
public void test() throws Exception{
Class<?> cls = Class.forName("chb.test.annotation.AnnotationDemo");
boolean flag = cls.isAnnotationPresent(MyAnnotation1.class);
if(flag){
System.out.println("判断类是annotation");
MyAnnotation1 annotation1=cls.getAnnotation(MyAnnotation1.class);
System.out.println(annotation1.value());
}
Method method = cls.getMethod("sayHello");
flag = method.isAnnotationPresent(MyAnnotation2.class) ;
if(flag){
System.out.println("判断方法也是annotation");
MyAnnotation2 annotation2=method.getAnnotation(MyAnnotation2.class);
System.out.println(annotation2.description()+"\t"+annotation2.isAnnotation());
}
}
}