1.java自带的标准注解
@Override @SuppressWarnings @Deprecated
package com.lt.annotation;
import java.util.ArrayList;
import java.util.List;
public class Test01 extends Object{
@Override
public String toString() {
return super.toString();
}
@SuppressWarnings("all")
public void test01(){
List list = new ArrayList();
}
@Deprecated
public static void test02(){
System.out.println("test……");
}
}
2.元注解
元注解:负责解释其他注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
ElementType[] value();
}
- @Retention:表示我们的注解在什么位置还有效(runtime > class > source),一般自定义注解都写runtime
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
RetentionPolicy value();
}
- @Document:表示是否将我们的注解生成在JavaDoc中
- @Inherited:子类可以继承父类的注解
- @Repeatable:该注解是Java8新增的注解,用于开发重复注解
3.自定义一个简单注解
@Target(value={ElementType.METHOD,ElementType.TYPE})
@Retention(value= RetentionPolicy.RUNTIME)
@interface MyAnnotation{
String name();
}
4.定义一个注解并获取
①定义注解
@Target(value = {ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotationTest2{
String name() default "默认值";
int age() default 0;
int id() default -1;
String[] schools() default {"西部开源","清华大学"};
}
②使用注解
@MyAnnotationTest2(name = "乐天")
public class Test03 {
@MyAnnotationTest2(name = "二狗儿",schools = {"南大"})
public void test01(){
}
@MyAnnotationTest2(name = "鸡蛋儿",schools = {"北大"})
public void test02(){
}
}
③获取类上的注解的参数值
public class Test04 {
public static void main(String[] args) {
Class<Test03> test03Class = Test03.class;
boolean annotation = test03Class.isAnnotationPresent(MyAnnotationTest2.class);
if(annotation){
MyAnnotationTest2 myAnnotationTest = test03Class.getAnnotation(MyAnnotationTest2.class);
System.out.println("name:" + myAnnotationTest.name());
System.out.println("age:" + myAnnotationTest.age());
System.out.println("id:" + myAnnotationTest.id());
}
}
}
输出:
name:乐天
age:0
id:-1
④获取方法上的注解的参数值
class GetAnnoMethod{
public static void main(String[] args) {
Method[] declaredMethods = Test03.class.getDeclaredMethods();
for (Method m : declaredMethods){
if(m.isAnnotationPresent(MyAnnotationTest2.class)){
System.out.println("name:" + m.getAnnotation(MyAnnotationTest2.class).name());
System.out.println("age:" + m.getAnnotation(MyAnnotationTest2.class).age());
System.out.println("id:" + m.getAnnotation(MyAnnotationTest2.class).id());
System.out.println("school:" + Arrays.toString(m.getAnnotation(MyAnnotationTest2.class).schools()));
System.out.println("**********************************");
}
}
}
}
输出:
name:二狗儿
age:0
id:-1
school:[南大]
**********************************
name:鸡蛋儿
age:0
id:-1
school:[北大]
**********************************
|