跟同学吹牛的时候,他说公司里的大牛写的注解他看不懂,我也的确是一知半解,只知道Spring用起来很爽,今天看Java核心技术卷二的时候,翻到了注解这一章,写的很好,于是就研究了一下。
一个简单的注解
package com.company;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
public class LearnAnnotation {
//定义注解,指定注解在运行时留存
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{
String name();
int age();
}
//使用注解
@MyAnnotation(name="Moon", age=21)
class Foo {
String name;
int age;
}
public static void main(String[] args) {
//检查Foo中是否存在MyAnnotation注解
if (Foo.class.isAnnotationPresent(MyAnnotation.class)){
//获取注解
MyAnnotation myAnnotation = Foo.class.getAnnotation(MyAnnotation.class);
System.out.print(String.format("Hello %s, your age is %s", myAnnotation.name(), myAnnotation.age()));
}
}
}
Spring注解实现
待续
参考资料
Java核心技术卷二
Java注解Annotation详解
深入理解Java:注解(Annotation)–注解处理器