当前位置: 移动技术网 > IT编程>开发语言>Java > java自定义注解接口实现方案

java自定义注解接口实现方案

2019年07月22日  | 移动技术网IT编程  | 我要评论
java注解是附加在代码中的一些元信息,用于一些工具在编译、运行时进行解析和使用,起到说明、配置的功能。
注解不会也不能影响代码的实际逻辑,仅仅起到辅助性的作用。包含在 java.lang.annotation 包中。
1、元注解
元注解是指注解的注解。包括 @retention @target @document @inherited四种。
1.1、@retention: 定义注解的保留策略
java代码
复制代码 代码如下:

@retention(retentionpolicy.source) //注解仅存在于源码中,在class字节码文件中不包含
@retention(retentionpolicy.class) //默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
@retention(retentionpolicy.runtime)//注解会在class字节码文件中存在,在运行时可以通过反射获取到

1.2、@target:定义注解的作用目标
java代码
复制代码 代码如下:

@target(elementtype.type) //接口、类、枚举、注解
@target(elementtype.field) //字段、枚举的常量
@target(elementtype.method) //方法
@target(elementtype.parameter) //方法参数
@target(elementtype.constructor) //构造函数
@target(elementtype.local_variable)//局部变量
@target(elementtype.annotation_type)//注解
@target(elementtype.package) ///包

elementtype 可以有多个,一个注解可以为类的,方法的,字段的等等
1.3、@document:说明该注解将被包含在javadoc中
1.4、@inherited:说明子类可以继承父类中的该注解
下面是自定义注解的一个例子
2、注解的自定义
java代码
复制代码 代码如下:

@retention(retentionpolicy.runtime)
@target(elementtype.method)
public @interface helloworld {
public string name() default "";
}

3、注解的使用,测试类
java代码
复制代码 代码如下:

public class sayhello {
@helloworld(name = " 小明 ")
public void sayhello(string name) {
system.out.println(name + "say hello world!");
}//www.heatpress123.net
}

4、解析注解
java的反射机制可以帮助,得到注解,代码如下:
java代码
复制代码 代码如下:

public class anntest {
public void parsemethod(class<?> clazz) {
object obj;
try {
// 通过默认构造方法创建一个新的对象
obj = clazz.getconstructor(new class[] {}).newinstance(
new object[] {});
for (method method : clazz.getdeclaredmethods()) {
helloworld say = method.getannotation(helloworld.class);
string name = "";
if (say != null) {
name = say.name();
system.out.println(name);
method.invoke(obj, name);
}
}
} catch (exception e) {
e.printstacktrace();
}
}
public static void main(string[] args) {
anntest t = new anntest();
t.parsemethod(sayhello.class);
}
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网