Java注解(Annotation)
(1) Annotation(注释)是JDK5.0及以后版本引入的。它可以用于创建文档,跟踪代码中的依赖性,甚至执行基本编译时检查。注释是以‘@注释名’在代码中存在的,根据注释参数的个数,我们可以将注释分为:标记注释、单值注释、完整注释三类。它们都不会直接影响到程序的语义,只是作为注释(标识)存在,我们可以通过反射机制编程实现对这些元数据的访问。另外,你可以在编译时选择代码里的注释是否只存在于源代码级,或者它也能在class文件中出现。
元数据的作用 如果要对于元数据的作用进行分类,目前还没有明确的定义,不过我们可以根据它所起的作用,大致可分为三类: 编写文档:通过代码里标识的元数据生成文档。 代码分析:通过代码里标识的元数据对代码进行分析。 编译检查:通过代码里标识的元数据让编译器能实现基本的编译检查。
基本内置注释
@Override
Java代码
1. package com.iwtxokhtd.annotation;
2. /**
3. * 测试Override注解 4. * @author Administrator
5. *
6. */
7. public class OverrideDemoTest {
8.
9. //@Override
10. public String tostring(){
11. return "测试注释";
12. }
13. }
package com.iwtxokhtd.annotation;
/**
* 测试Override注解 * @author Administrator
*
*/
public class OverrideDemoTest {
//@Override
public String tostring(){
return "测试注释";
}
}
@Deprecated的作用是对不应该在使用的方法添加注释,当编程人员使用这些方法时,将会在编译时显示提示信息,它与javadoc里的@deprecated标记有相同的功能,准确的说,它还不如javadoc @deprecated,因为它不支持参数,使用@Deprecated的示例代码示例如下:
Java代码
1. package com.iwtxokhtd.annotation;
2. /**
3. * 测试Deprecated注解 4. * @author Administrator
5. *
6. */
7. public class DeprecatedDemoTest {
8. public static void main(String[] args) {
9. //使用DeprecatedClass里声明被过时的方法
10. DeprecatedClass.DeprecatedMethod();
11. }
12. }
13. class DeprecatedClass{
14. @Deprecated
15. public static void DeprecatedMethod() {
16. }
17. }
package com.iwtxokhtd.annotation;
/**
* 测试Deprecated注解 * @author Administrator
*
*/
public class DeprecatedDemoTest {
public static void main(String[] args) {
//使用DeprecatedClass里声明被过时的方法 DeprecatedClass.DeprecatedMethod();
}
}
class DeprecatedClass{
@Deprecated
public static void DeprecatedMethod() {
}
}
@SuppressWarnings,其参数有:
deprecation,使用了过时的类或方法时的警告
unchecked,执行了未检查的转换时的警告
fallthrough,当 Switch
程序块直接通往下一种情况而没有 Break 时的警告
path,在类路径、源文件路径等中有不存在的路径时的警告
serial,当在可序列化的类上缺少 serialVersionUID
定义时的警告
finally ,任何 finally
子句不能正常完成时的警告
all,关于以上所有情况的警告
Java代码
1. package com.iwtxokhtd.annotation;
2.
3. import java.util.ArrayList;
4. import java.util.List;
5.
6. public class SuppressWarningsDemoTest {
7.
8. public static List list=new ArrayList();
9. @SuppressWarnings("unchecked")
10. public void add(String data){
11. list.add(data);
12. }
13. }
package com.iwtxokhtd.annotation;
import java.util.ArrayList;
import java.util.List;
public class SuppressWarningsDemoTest {
public static List list=new ArrayList();
@SuppressWarnings("unchecked")
public void add(String data){
list.add(data);
}
}
(2)自定义注释
它类似于新创建一个接口类文件,但为了区分,我们需要将它声明为@interface,如下例:
Java代码
1. public @interface NewAnnotation {
2. }
public @interface NewAnnotation {
}
使用自定义的注释类型
Java代码
1. public class AnnotationTest {
2. @NewAnnotation
3. public static void main(String[] args) {
4. }
5. }
public class AnnotationTest {
@NewAnnotation
public static void main(String[] args) {
}
}
为自定义注释添加变量
Java代码
1. public @interface NewAnnotation {
2. String value();
3. }
public @interface NewAnnotation {
String value();
}
Java代码
1. public class AnnotationTest {
2. @NewAnnotation("main method")
3. public static void main(String[] args) {
4. saying();
5. }
6. @NewAnnotation(value = "say method")
7. public static void saying() {
8. }
9. }
public class AnnotationTest {
@NewAnnotation("main method")
public static void main(String[] args) {
saying();
}
@NewAnnotation(value = "say method")
public static void saying() {
}
}
定义一个枚举类型,然后将参数设置为该枚举类型,并赋予默认值
Java代码
1. public @interface Greeting {
2. public enum FontColor{
3. BLUE,RED,GREEN
4. };
5. String name();
6. FontColor fontColor() default FontColor.RED;}
7. }
public @interface Greeting {
public enum FontColor{
BLUE,RED,GREEN
};
String name();
FontColor fontColor() default FontColor.RED;}
}
这里有两种选择,其实变数也就是在赋予默认值的参数上,我们可以选择使用该默认值,也可以重新设置一个值来替换默认值
Java代码
1. @NewAnnonation("main method")
2. public static void main(String[] args) {
3. saying();
4. sayHelloWithDefaultFontColor();
5. sayHelloWithRedFontColor();
6.
7. }
8. @NewAnnonation("say method")
9. public static void saying(){
10.
11. }
12. //此时的fontColor为默认的RED
13. @Greeting(name="defaultfontcolor")
14. public static void sayHelloWithDefaultFontColor() {
15.
16. }
17. //现在将fontColor改为BLUE
18. @Greeting(name="notdefault",fontColor=Greeting.FontColor.BLUE)
19. public static void sayHelloWithRedFontColor() {
20.
21. }
@NewAnnonation("main method")
public static void main(String[] args) {
saying();
sayHelloWithDefaultFontColor();
sayHelloWithRedFontColor();
}
@NewAnnonation("say method")
public static void saying(){
}
//此时的fontColor为默认的RED
@Greeting(name="defaultfontcolor")
public static void sayHelloWithDefaultFontColor() {
}
//现在将fontColor改为BLUE
@Greeting(name="notdefault",fontColor=Greeting.FontColor.BLUE)
public static void sayHelloWithRedFontColor() {
}
(3)注释的高级应用
限制注释的使用范围
用@Target指定ElementType属性
Java代码
1. package java.lang.annotation;
2. public enum ElementType {
3. TYPE,
4. // 用于类,接口,枚举但不能是注释
5. FIELD,
6. // 字段上,包括枚举值
7. METHOD,
8. // 方法,不包括构造方法
9. PARAMETER,
10. // 方法的参数
11. CONSTRUCTOR,
12. //构造方法
13. LOCAL_VARIABLE,
14. // 本地变量或catch语句
15. ANNOTATION_TYPE,
16. // 注释类型(无数据)
17. PACKAGE
18. // Java包
19. }
package java.lang.annotation;
public enum ElementType {
TYPE,
// 用于类,接口,枚举但不能是注释 FIELD,
// 字段上,包括枚举值
METHOD,
// 方法,不包括构造方法 PARAMETER,
// 方法的参数 CONSTRUCTOR,
//构造方法 LOCAL_VARIABLE,
// 本地变量或catch语句 ANNOTATION_TYPE,
// 注释类型(无数据)
PACKAGE
// Java包
}
注解保持性策略
Java代码
1. //限制注解使用范围
2. @Target({ElementType.METHOD,ElementType.CONSTRUCTOR})
3. public @interface Greeting {
4.
5. //使用枚举类型
6. public enum FontColor{
7. BLUE,RED,GREEN
8. };
9. String name();
10. FontColor fontColor() default FontColor.RED;
11. }
//限制注解使用范围 @Target({ElementType.METHOD,ElementType.CONSTRUCTOR})
public @interface Greeting {
//使用枚举类型 public enum FontColor{
BLUE,RED,GREEN
};
String name();
FontColor fontColor() default FontColor.RED;
}
在Java编译器编译时,它会识别在源代码里添加的注释是否还会保留,这就是RetentionPolicy。下面是Java定义的RetentionPolicy枚举:
编译器的处理有三种策略:
将注释保留在编译后的类文件中,并在第一次加载类时读取它
将注释保留在编译后的类文件中,但是在运行时忽略它
按照规定使用注释,但是并不将它保留到编译后的类文件中
Java代码
1. package java.lang.annotation;
2. public enum RetentionPolicy {
3. SOURCE,
4. // 此类型会被编译器丢弃
5. CLASS,
6. // 此类型注释会保留在class文件中,但JVM会忽略它
7. RUNTIME
8. // 此类型注释会保留在class文件中,JVM会读取它
9. }
package java.lang.annotation;
public enum RetentionPolicy {
SOURCE,
// 此类型会被编译器丢弃
CLASS,
// 此类型注释会保留在class文件中,但JVM会忽略它
RUNTIME
// 此类型注释会保留在class文件中,JVM会读取它
}
Java代码
1. //让保持性策略为运行时态,即将注解编码到class文件中,让虚拟机读取
2. @Retention(RetentionPolicy.RUNTIME)
3. public @interface Greeting {
4.
5. //使用枚举类型
6. public enum FontColor{
7. BLUE,RED,GREEN
8. };
9. String name();
10. FontColor fontColor() default FontColor.RED;
11. }
//让保持性策略为运行时态,即将注解编码到class文件中,让虚拟机读取 @Retention(RetentionPolicy.RUNTIME)
public @interface Greeting {
//使用枚举类型 public enum FontColor{
BLUE,RED,GREEN
};
String name();
FontColor fontColor() default FontColor.RED;
}
文档化功能
Java提供的Documented元注释跟Javadoc的作用是差不多的,其实它存在的好处是开发人员可以定制Javadoc不支持的文档属性,并在开发中应用。它的使用跟前两个也是一样的,简单代码示例如下:
Java代码
1. //让它定制文档化功能
2. //使用此注解时必须设置RetentionPolicy为RUNTIME
3. @Documented
4. public @interface Greeting {
5.
6. //使用枚举类型
7. public enum FontColor{
8. BLUE,RED,GREEN
9. };
10. String name();
11. FontColor fontColor() default FontColor.RED;
12. }
//让它定制文档化功能 //使用此注解时必须设置RetentionPolicy为RUNTIME
@Documented
public @interface Greeting {
//使用枚举类型 public enum FontColor{
BLUE,RED,GREEN
};
String name();
FontColor fontColor() default FontColor.RED;
}
标注继承
Java代码
1. //让它允许继承,可作用到子类
2. @Inherited
3. public @interface Greeting {
4.
5. //使用枚举类型
6. public enum FontColor{
7. BLUE,RED,GREEN
8. };
9. String name();
10. FontColor fontColor() default FontColor.RED;
11. }
//让它允许继承,可作用到子类 @Inherited
public @interface Greeting {
//使用枚举类型 public enum FontColor{
BLUE,RED,GREEN
};
String name();
FontColor fontColor() default FontColor.RED;
}
(4)读取注解信息
属于重点,在系统中用到注解权限时非常有用,可以精确控制权限的粒度
Java代码
1. package com.iwtxokhtd.annotation;
2. import java.lang.annotation.Annotation;
3. import java.lang.reflect.Method;
4.
5. //读取注解信息
6. public class ReadAnnotationInfoTest {
7. public static void main(String[] args)throws Exception {
8. //测试AnnotationTest类,得到此类的类对象
9. Class c=Class.forName("com.iwtxokhtd.annotation.AnnotationTest");
10. //获取该类所有声明的方法
11. Method []methods=c.getDeclaredMethods();
12. //声明注解集合
13. Annotation[] annotations;
14. //遍历所有的方法得到各方法上面的注解信息
15. for(Method method:methods){
16. //获取每个方法上面所声明的所有注解信息
17. annotations=method.getDeclaredAnnotations();
18. //再遍历所有的注解,打印其基本信息
19. for(Annotation an:annotations){
20. System.out.println("方法名为:"+method.getName()+"
其上面的注解为:"+an.annotationType().getSimpleName());
21. Method []meths=an.annotationType().getDeclaredMethods();
22. //遍历每个注解的所有变量
23. for(Method meth:meths){
24. System.out.println("注解的变量名为:"+meth.getName());
25. }
26.
27. }
28. }
29.
30. }
31.
32. }
package com.iwtxokhtd.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
//读取注解信息 public class ReadAnnotationInfoTest {
public static void main(String[] args)throws Exception {
//测试AnnotationTest类,得到此类的类对象 Class c=Class.forName("com.iwtxokhtd.annotation.AnnotationTest");
//获取该类所有声明的方法 Method []methods=c.getDeclaredMethods();
//声明注解集合 Annotation[] annotations;
//遍历所有的方法得到各方法上面的注解信息 for(Method method:methods){
//获取每个方法上面所声明的所有注解信息 annotations=method.getDeclaredAnnotations();
//再遍历所有的注解,打印其基本信息 for(Annotation an:annotations){
System.out.println("方法名为:"+method.getName()+"
其上面的注解为:"+an.annotationType().getSimpleName());
Method []meths=an.annotationType().getDeclaredMethods();
//遍历每个注解的所有变量 for(Method meth:meths){
System.out.println("注解的变量名为:"+meth.getName());
}
}
}
}
}
|
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
注解(Annotation) 为我们在代码中天界信息提供了一种形式化的方法,是我们可以在稍后
某个时刻方便地使用这些数据(通过 解析注解 来使用这些数据)。
注解的语法比较简单,除了@符号的使用以外,它基本上与java的固有语法一致,java内置了三种
注解,定义在java.lang包中。
@Override 表示当前方法是覆盖父类的方法。
@Deprecated 表示当前元素是不赞成使用的。
@SuppressWarnings 表示关闭一些不当的编译器警告信息。
下面是一个定义注解的实例
- packageTest_annotation;
-
importjava.lang.annotation.Documented;
-
importjava.lang.annotation.Inherited;
-
importjava.lang.annotation.Retention;
-
importjava.lang.annotation.Target;
-
importjava.lang.annotation.ElementType;
-
importjava.lang.annotation.RetentionPolicy;
-
-
@Target(ElementType.METHOD)
-
@Retention(RetentionPolicy.RUNTIME)
-
@Documented
-
@Inherited
-
-
public@interfaceTest{
-
publicintid();
-
publicStringdescription()default"nodescription";
- }
package Test_annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
/*
* 元注解@Target,@Retention,@Documented,@Inherited
*
* @Target 表示该注解用于什么地方,可能的 ElemenetType 参数包括:
* ElemenetType.CONSTRUCTOR 构造器声明
* ElemenetType.FIELD 域声明(包括 enum 实例)
* ElemenetType.LOCAL_VARIABLE 局部变量声明
* ElemenetType.METHOD 方法声明
* ElemenetType.PACKAGE 包声明
* ElemenetType.PARAMETER 参数声明
* ElemenetType.TYPE 类,接口(包括注解类型)或enum声明
*
* @Retention 表示在什么级别保存该注解信息。可选的 RetentionPolicy 参数包括:
* RetentionPolicy.SOURCE 注解将被编译器丢弃
* RetentionPolicy.CLASS 注解在class文件中可用,但会被VM丢弃
* RetentionPolicy.RUNTIME VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息。
*
* @Documented 将此注解包含在 javadoc 中
*
* @Inherited 允许子类继承父类中的注解
*
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
/*
* 定义注解 Test
* 注解中含有两个元素 id 和 description
* description 元素 有默认值 "no description"
*/
public @interface Test {
public int id();
public String description() default "no description";
}
下面是一个使用注解 和 解析注解的实例
- packageTest_annotation;
-
importjava.lang.reflect.Method;
-
publicclassTest_1{
-
-
@Test(id=1,description="hellomethod_1")
-
publicvoidmethod_1(){
- }
-
@Test(id=2)
-
publicvoidmethod_2(){
- }
-
@Test(id=3,description="lastmethod")
-
publicvoidmethod_3(){
- }
-
-
publicstaticvoidmain(String[]args){
-
Method[]methods=Test_1.class.getDeclaredMethods();
-
for(Methodmethod:methods){
-
-
booleanhasAnnotation=method.isAnnotationPresent(Test.class);
-
if(hasAnnotation){
-
-
Testannotation=method.getAnnotation(Test.class);
-
System.out.println("Test(method="+method.getName()
-
+",id="+annotation.id()+",description="
-
+annotation.description()+")");
- }
- }
- }
- }
package Test_annotation;
import java.lang.reflect.Method;
public class Test_1 {
/*
* 被注解的三个方法
*/
@Test(id = 1, description = "hello method_1")
public void method_1() {
}
@Test(id = 2)
public void method_2() {
}
@Test(id = 3, description = "last method")
public void method_3() {
}
/*
* 解析注解,将Test_1类 所有被注解方法 的信息打印出来
*/
public static void main(String[] args) {
Method[] methods = Test_1.class.getDeclaredMethods();
for (Method method : methods) {
/*
* 判断方法中是否有指定注解类型的注解
*/
boolean hasAnnotation = method.isAnnotationPresent(Test.class);
if (hasAnnotation) {
/*
* 根据注解类型返回方法的指定类型注解
*/
Test annotation = method.getAnnotation(Test.class);
System.out.println("Test( method = " + method.getName()
+ " , id = " + annotation.id() + " , description = "
+ annotation.description() + " )");
}
}
}
}
输出结果如下:
Test( method = method_1 , id = 1 , description = hello method_1 )
Test( method = method_2 , id = 2 , description = no description )
Test( method = method_3 , id = 3 , description = last method )
分享到:
相关推荐
java注解代码java注解代码java注解代码java注解代码java注解代码java注解代码java注解代码java注解代码java注解代码java注解代码java注解代码java注解代码java注解代码java注解代码java注解代码java注解代码java注解...
java注解和反射的个人学习笔记
Java注解实现
JAVA注释模板以及详细设置解释等等。 注释模板 如何设置
eclipse中java类注释模板,有需要的朋友可以参考使用。
超级好用的 java 注释模板,吐血总结,整理。吐血总结,整理。
java注释全解,内容全面,包括hibernate注解、Java注解、Spring注解、SSH全注解等内容,分为4个文档介绍。另附一些精品java学习资料,欢迎大家下载学习。
java 注释模板 java 注释模板 java 注释模板 java 注释模板java 注释模板java 注释模板java 注释模板java 注释模板java 注释模板java 注释模板java 注释模板java 注释模板java 注释模板java 注释模板java 注释模板
Eclipse Java 注释模板,设置后可以使用快捷键快速生成文档注释,版本信息等。
主要包括:普通java注解,hibernate注解,spring注解,struts2注解,对于学习注解的朋友有很大的帮助!
简述java注解功能及用法,有代码示例。看起来还成,比较简单,学spring注入的时候要用到注解注入的话,本书属于必看版。
自己做得java项目注释统计工具,可统计代码行数,注释行数,能统计各种注释样式,能看统计详细情况,能生成报表,可自由控制合格率!算法高效!
如果你想知道java annotation是什么?你可以看看
Java代码注释率检查器
java 自定义注解验证 可自己添加所需要的注解,本案例中只写了三个自定义注解类 本案例只花了半天时间,如有不好之处请多提提意见。谢谢!
有关于java的注释规范的详细描述,单行注释、多行注释、分块注释等这些java的三种注释方式
包括Java自定义注解以及包括自定义注解的应用实例。以及注解相关知识的注解
入门级java 注解学习示例代码
Java注释的良好习惯,方便项目的交接和事后的维护与整理,是一个很好的帮助自己养成编码习惯的工具,效果图在我的博文有记录,有需要的伙伴可以自行下载哦~
java 通过反射获取类上注解,方法上注解,注解里的值及方法参数,项目为maven项目。导入时记得选择maven项目