当前位置: 移动技术网 > IT编程>开发语言>Java > Java 注解的使用实例详解

Java 注解的使用实例详解

2019年07月22日  | 移动技术网IT编程  | 我要评论

java 注解的使用

 注解的使用非常简单,只需在需要注解的地方标明某个注解即可,例如在方法上注解:

public class test { 
@override 
public string tostring() { 
return "override it"; 
} 
}

例如在类上注解:

@deprecated 
public class test { 
}

所以java内置的注解直接使用即可,但很多时候我们需要自己定义一些注解,例如常见的spring就用了大量的注解来管理对象之间的依赖关系。下面看看如何定义一个自己的注解,下面实现这样一个注解:通过@test向某类注入一个字符串,通过@testmethod向某个方法注入一个字符串。

1.创建test注解,声明作用于类并保留到运行时,默认值为default。

@target({elementtype.type}) 
@retention(retentionpolicy.runtime) 
public @interface test { 
string value() default "default"; 
}

2.创建testmethod注解,声明作用于方法并保留到运行时。

@target({elementtype.method}) 
@retention(retentionpolicy.runtime) 
public @interface testmethod { 
string value(); 
}

3.测试类,运行后输出default和tomcat-method两个字符串,因为@test没有传入值,所以输出了默认值,而@testmethod则输出了注入的字符串。

@test() 
public class annotationtest { 
@testmethod("tomcat-method") 
public void test(){ 
} 
public static void main(string[] args){ 
test t = annotationtest.class.getannotation(test.class); 
system.out.println(t.value()); 
testmethod tm = null; 
try { 
tm = annotationtest.class.getdeclaredmethod("test",null).getannotation(testmethod.class); 
} catch (exception e) { 
e.printstacktrace(); 
} 
system.out.println(tm.value()); 
} 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

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

相关文章:

验证码:
移动技术网