一般填“all” ,压制所有的警告
可以查看JDK自己的注解的实现方式:
自写两个注解:
package interfaced;
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;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Hello {
int age();
String name();
}
package interfaced;
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;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value=ElementType.FIELD)
public @interface World {
int number();
}
需要注解的类:
package entity;
import interfaced.Hello;
import interfaced.World;
@Hello(age = 10, name = "Jack")
public class Worker {
@World(number = 1000)
private int num;
public void SetNum(int num) {
this.num = num;
}
public int GetNum() {
return num;
}
}
主类:
package practiceDemo1;
import java.lang.reflect.Field;
import java.util.Arrays;
import entity.Worker;
import interfaced.Hello;
import interfaced.World;
public class Test01 {
public static void main(String[] args) throws Exception{
Worker wor = new Worker();
// 1、 获取 Worker类上的注解 @Hello
Hello hello = wor.getClass().getAnnotation(Hello.class);
int age = hello.age();
String name = hello.name();
System.out.println(age+" "+ name);
// 2、 获取Worker类中 num 变量上的注解 @World ,需要借助 Field ,因为num非类,所以要映射成一个类fle
Field fle = wor.getClass().getDeclaredField("num");
World world = fle.getAnnotation(World.class);
wor.SetNum(world.number());
System.out.println(wor.GetNum());
}
}
运行结果:
10 Jack
1000