一般填“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