@interface使用
1.@interface自定义注解
<1>@interface自定义注解自动继承了java.lang.annotation.Annotation接口,由编译程序自动完成其他细节。
<2>在定义注解时,不能继承其他的注解或接口。
<3>使用@interface来声明一个注解,
1>.每一个方法实际上是声明了一个配置参数,
2>.方法的名称就是参数的名称,
3>.返回值类型就是参数的类型,(返回值类型只能是基本类型、Class、String、enum)
4>.可以通过default来声明参数的默认值
@Target
指定注解使用的目标范围(类、方法、字段等),其参考值见类的定义:java.lang.annotation.ElementType
@Documented
指定被标注的注解会包含在javadoc中。
@Retention
指定注解的生命周期(源码、class文件、运行时),其参考值见类的定义:java.lang.annotation.RetentionPolicy
@Inherited
指定子类可以继承父类的注解,只能是类上的注解,方法和字段的注解不能继承。即如果父类上的注解是@Inherited修饰的就能被子类继承。
@Native
指定字段是一个常量,其值引用native code。
@Repeatable
注解上可以使用重复注解,即可以在一个地方可以重复使用同一个注解,像spring中的包扫描注解就使用了这个。
2.举例说明,分别作用在类,方法,属性上的注解
<1>.作用在属性上注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface FiledAnnotation {
String value() default "GetFiledAnnotation";
}
<2>.作用在方法上注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MethodAnnotation {
String name() default "MethodAnnotation";
String url() default "https://www.cnblogs.com";
}
<3>.作用在类上注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface TypeAnnotation {
String value() default "Is-TypeAnnotation";
}
<4>.使用自定义注解
@TypeAnnotation(value = "doWork")
public class Worker {
@FiledAnnotation(value = "优快云博客")
private String myfield = "";
@MethodAnnotation()
public String getDefaultInfo() {
return "do the getDefaultInfo method";
}
@MethodAnnotation(name = "百度", url = "www.baidu.com")
public String getDefineInfo() {
return "do the getDefineInfo method";
}
}
<5>.测试自定义注解
public class TestMain {
public static void main(String[] args) throws Exception {
Class cls = Class.forName("com.zbz.annotation.pattern3.Worker");
Method[] method = cls.getMethods();
/**判断Worker类上是否有TypeAnnotation注解*/
boolean flag = cls.isAnnotationPresent(TypeAnnotation.class);
/**获取Worker类上是TypeAnnotation注解值*/
if (flag) {
TypeAnnotation typeAnno = (TypeAnnotation) cls.getAnnotation(TypeAnnotation.class);
System.out.println("@TypeAnnotation值:" + typeAnno.value());
}
/**方法上注解*/
List<Method> list = new ArrayList<Method>();
for (int i = 0; i < method.length; i++) {
list.add(method[i]);
}
for (Method m : list) {
MethodAnnotation methodAnno = m.getAnnotation(MethodAnnotation.class);
if (methodAnno == null)
continue;
System.out.println( "方法名称:" + m.getName());
System.out.println("方法上注解name = " + methodAnno.name());
System.out.println("方法上注解url = " + methodAnno.url());
}
/**属性上注解*/
List<Field> fieldList = new ArrayList<Field>();
for (Field f : cls.getDeclaredFields()) {// 访问所有字段
FiledAnnotation filedAno = f.getAnnotation(FiledAnnotation.class);
System.out.println( "属性名称:" + f.getName());
System.out.println("属性注解值FiledAnnotation = " + filedAno.value());
}
}
}