注解说明
注解其实是代码里的特殊标记,这些标记可以在编译、类加载、运行时被读取,并执行相应的处理。
通过使用注解,可以在class源文件嵌入一些补充信息。
基本注解
- 限定充血父类方法:@Override
- 限定某个程序类、方法已过时:@Deprecated
- 抑制编译器警告:@SuppressWarnings
- “堆污染”警告:@SafeVarargs
- 函数式接口:@FunctionalInterface
元注解
- 设置注解保留时间:@Retention
- 设置注解修饰的程序单元:@Target
- 该注解会生成文档:@Documented
- 设置继承性:@Inherited
定义注解
使用@interface关键字
public @interface Test{
}
使用该注解
@Test
public class MyClass{
@Test
public void info(){
}
}
注解设置成员变量,注解中的成员变量都是以方法的形式定义
public @interface MyTag{
String name() default "hello";
int age() default 18;
}
使用注解指定变量
public class Test{
@MyTag(name="张三",age=26)
public void info(){
}
}
获取注解信息
通过反射获取该类上注解的信息
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyTag {
// 注解中的成员变量必须以方法的形式定义
String name() default "name";
int age() default 18;
}
@Test
public class MyClass {
@Test
public void info() {
}
@MyTag(name="a",age=12)
public void test() {
}
}
public static void main(String[] args) throws NoSuchMethodException, SecurityException, ClassNotFoundException {
Annotation[] annotations = Class.forName("com.chen.MyClass").getMethod("test").getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
}
输出:@com.chen.MyTag(name=a, age=12)
获取详细的信息
public static void main(String[] args) throws NoSuchMethodException, SecurityException, ClassNotFoundException {
Annotation[] annotations = Class.forName("com.chen.MyClass").getMethod("test").getAnnotations();
for (Annotation annotation : annotations) {
if (annotation instanceof MyTag) {
System.out.println("name:"+((MyTag)annotation).name());
System.out.println("age:"+((MyTag)annotation).age());
}
}
}
输出:
name:a
age:12