[b]Spring自定义注解[/b]
[b]@Target(ElementType.METHOD)[/b]
用来说明该注解可以被声明在那些元素之前。
ElementType.TYPE:说明该注解只能被声明在一个类前。
ElementType.FIELD:说明该注解只能被声明在一个类的字段前。
ElementType.METHOD:说明该注解只能被声明在一个类的方法前。
ElementType.PARAMETER:说明该注解只能被声明在一个方法参数前。
ElementType.CONSTRUCTOR:说明该注解只能声明在一个类的构造方法前。
ElementType.LOCAL_VARIABLE:说明该注解只能声明在一个局部变量前。
ElementType.ANNOTATION_TYPE:说明该注解只能声明在一个注解类型前。
ElementType.PACKAGE:说明该注解只能声明在一个包名前。
[b]@Retention(RetentionPolicy.RUNTIME)[/b]
RetentionPolicy.SOURCE : 注解只保留在源文件中
RetentionPolicy.CLASS : 注解保留在class文件中,在加载到JVM虚拟机时丢弃
RetentionPolicy.RUNTIME : 注解保留在程序运行期间,此时可以通过反射获得定义在某个类上的所有注解。
[b]@Inherited[/b]
1.允许子类继承父类的注解。
2.注意:在这种情况下,并不是应用在所有的地方,只有父类在在"类"这个级别上使用的annotation才能被继承,
如果声明在方法、变量等地方的annotation不会被继承
[b]@Documented[/b](可以不管)
[b]例子:[/b]
Person.java
参考原文:[url]http://www.tuicool.com/articles/2MRZJn[/url]
参考原文:[url]http://xiangdefei.iteye.com/blog/1044199[/url]
参考原文:[url]http://blog.csdn.net/maguanghui_2012/article/details/69372209[/url]
[b]@Target(ElementType.METHOD)[/b]
用来说明该注解可以被声明在那些元素之前。
ElementType.TYPE:说明该注解只能被声明在一个类前。
ElementType.FIELD:说明该注解只能被声明在一个类的字段前。
ElementType.METHOD:说明该注解只能被声明在一个类的方法前。
ElementType.PARAMETER:说明该注解只能被声明在一个方法参数前。
ElementType.CONSTRUCTOR:说明该注解只能声明在一个类的构造方法前。
ElementType.LOCAL_VARIABLE:说明该注解只能声明在一个局部变量前。
ElementType.ANNOTATION_TYPE:说明该注解只能声明在一个注解类型前。
ElementType.PACKAGE:说明该注解只能声明在一个包名前。
[b]@Retention(RetentionPolicy.RUNTIME)[/b]
RetentionPolicy.SOURCE : 注解只保留在源文件中
RetentionPolicy.CLASS : 注解保留在class文件中,在加载到JVM虚拟机时丢弃
RetentionPolicy.RUNTIME : 注解保留在程序运行期间,此时可以通过反射获得定义在某个类上的所有注解。
[b]@Inherited[/b]
1.允许子类继承父类的注解。
2.注意:在这种情况下,并不是应用在所有的地方,只有父类在在"类"这个级别上使用的annotation才能被继承,
如果声明在方法、变量等地方的annotation不会被继承
[b]@Documented[/b](可以不管)
[b]例子:[/b]
Description.java
@Target(ElementType.METHOD )
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Description {
String desc();
String author();
int age() default 18;
}
Person.java
public class Person {
@Description(desc="yong",author="xing",age=19)
public void sayHello(){
System.out.println("Hello");
}
@Description(desc="yong",author="xing",age=19)
public void sayHello2(){
System.out.println("Hello2");
}
public static void main(String[] args) {
Person person = new Person();
person.sayHello();
Method[] m = Person.class.getDeclaredMethods(); //得到一个类的所有方法
System.out.println("len = " + m.length);
for (Method m2 : m) {
Description description = m2.getAnnotation(Description.class);//得到方法上的注解
System.out.println("description = " + description);
if (description != null) {
System.out.println("description:" + description.desc() + " "
+ description.author() + " "+ description.age() + " "); 得到注解上的内容
}
}
}
}
参考原文:[url]http://www.tuicool.com/articles/2MRZJn[/url]
参考原文:[url]http://xiangdefei.iteye.com/blog/1044199[/url]
参考原文:[url]http://blog.csdn.net/maguanghui_2012/article/details/69372209[/url]