创建
创建自定义注解与编写接口很相似,除了在接口关键字前有个@符号。
注意以下几点:
- 注解方法不能有参数。
- 注解方法的返回类型局限于原始类型,字符串,枚举,注解,或以上类型构成的数组。
- 注解方法可以包含默认值。
- 注解可以包含与其绑定的元注解,元注解为注解提供信息,有四种元注解类型:
- @Documented – 表示使用该注解的元素应被javadoc或类似工具文档化,应用于类型声明,类型声明的注解会影响客户端对注解元素的使用。如果一个类型声明添加了Documented注解,那么它的注解会成为被注解元素的公共API的一部分。
- @Target – 表示支持注解的程序元素的种类,有TYPE, METHOD, CONSTRUCTOR, FIELD等等。如果Target元注解不存在,那么该注解就可以使用在任何程序元素之上。
- @Inherited – 表示一个注解类型会被自动继承,如果用户在类声明的时候查询注解类型,同时类声明中也没有这个类型的注解,那么注解类型会自动查询该类的父类,这个过程将会不停地重复,直到该类型的注解被找到为止,或是到达类结构的顶层(Object)。
- @Retention – 表示注解类型保留时间的长短,它接收RetentionPolicy参数,可能的值有SOURCE, CLASS, 以及RUNTIME。
实践
以下是一个简单自定义注解的实现过程:
首先创建自定义注解类Annotations,代码如下:
package com.springboot.action.saas.common.logging.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//在程序运行时可以获取到注解
@Retention(RetentionPolicy.RUNTIME)
//注解运用的目标,给类的方法进行注解
@Target({ElementType.METHOD})
//定义注解
public @interface MyAnnotations {
//方法名定义了该成员变量的名字,其返回值定义了该成员变量的类型,设置默认返回值
long time() default -1;
}
写一个简单的实现类:
package com.springboot.action.saas.common.logging.annotation;
import java.util.Date;
/**
*
*/
public class DoSomeThing {
public void test() {
System.out.println("执行自定义注解");
System.out.println("执行自定义注解结束时间:"+new Date());
}
}
然后写一个使用自定义注解的类:
package com.springboot.action.saas.common.logging.annotation;
public class Test {
//私有成员变量
private DoSomeThing doSomeThing= new DoSomeThing();
//构造函数
@MyAnnotations
public void test(){
doSomeThing.test();
}
}
最后利用反射,使注解可以使用:
package com.springboot.action.saas.common.logging.annotation;
import java.lang.reflect.Method;
import java.util.Date;
// 反射注解
public class AnnotationsRunner {
public static void main(String[] args) throws Exception {
System.out.println("执行自定义注解开始时间:"+new Date());
Class testClass = Test.class;
//返回所有public的方法
Method[] publicMethods = testClass.getMethods();
//遍历方法list
for (Method method : publicMethods) {
// 判定指定类型的是否有注解
boolean flag = testClass.isAnnotationPresent(MyAnnotations.class);
// 判定注解结果
if (flag) {
//如果有注解,反射调用执行对象的目标方法,这里会执行Test构造函数
method.invoke(testClass.newInstance(), null);
}
}
}
}
网友评论