Java中的元注解有哪些?
Java中提供了4个元注解,
- **@Target:**元注解的作用是负责注解其它注解。
package com.company;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target(value = {ElementType.METHOD,ElementType.TYPE})
@interface MyZhujie{
}
@MyZhujie
class Test{
@MyZhujie
public void test(){
}
}
- **@Retention:(保留策略)**保留策略定义了该注解被保留的时间长短;runtime>class>source
其中,**SOURCE:**表示在源文件中有效(即源文件保留);**CLASS:**表示在class文件中有效(即class保留);**RUNTIME:表示在运行时有效(即运行时保留)。例如,@Retention(RetentionPolicy.RUNTIME)**标注表示该注解在运行时有效。
package com.company;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(value = RetentionPolicy.RUNTIME)
@interface MyZhujie{
}
@MyZhujie
class Test{
@MyZhujie
public void test(){
}
}
- **@Documented:**该注解用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被javadoc此类的工具文档化。Documented是一个标记注解,没有成员。关键源码如下:
- **@Inherited:**该注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。
注解的作用:
代替繁杂的配置文件,简化开发。
如何定义一个注解?
package com.company;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value = {ElementType.METHOD,ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@interface MyZhujie {
String value();
int value1();
int age() default 100;//默认值
}
class Test {
@MyZhujie(value1=100,value="hello")
public void test() {
}
}