Java 注释

Java 注释提供有关代码的信息. Java 注释对他们注释的代码没有直接影响. 在 java 注释教程中,我们将研究以下内容;

  1. 内置的Java注释
  2. 如何编写自定义注释
  3. 注释的使用和如何使用Reflection API(/社区/教程/java-reflection-example-tutorial)解析注释

java 评论

java annotations, annotations in java, java annotation example, java annotations tutorial, java custom annotation Java 1.5 introduced annotations and now it's heavily used in Java EE frameworks like Hibernate, Jersey, and Spring. Java Annotation is metadata about the program embedded in the program itself. It can be parsed by the annotation parsing tool or by the compiler. We can also specify annotation availability to either compile time only or till runtime. Before java annotations, program metadata was available through java comments or by Javadoc but annotation offers more than that. Annotations metadata can be available at runtime too and annotation parsers can use it to determine the process flow. For example, in Jersey webservice we add PATH annotation with URI string to a method and at runtime, jersey parses it to determine the method to invoke for given URI pattern.

Java 定制注释

创建自定义注释类似于写一个界面,除非界面关键字是以 _@ 符号为前缀。我们可以在注释中声明方法。

 1package com.journaldev.annotations;
 2
 3import java.lang.annotation.Documented;
 4import java.lang.annotation.ElementType;
 5import java.lang.annotation.Inherited;
 6import java.lang.annotation.Retention;
 7import java.lang.annotation.RetentionPolicy;
 8import java.lang.annotation.Target;
 9
10@Documented
11@Target(ElementType.METHOD)
12@Inherited
13@Retention(RetentionPolicy.RUNTIME)
14public @interface MethodInfo{
15    String author() default "Pankaj";
16    String date();
17    int revision() default 1;
18    String comments();
19}

关于 java 注释的一些重要点是:

  1. 注释方法不能有参数
  2. 注释方法的返回类型仅限于原始字符、字符串、字符串、注释或它们的数组
  3. Java注释方法可以有默认值
  4. 注释可以附有元注释。

Java 中的 Meta 注释

有五种类型的Meta注释:

  1. 联合国 * ** 文件** -- -- 表明使用这一注释的元素应当由javadoc和类似工具加以记录。 此类声明应用于说明其说明影响客户使用附加说明要素的类型。 如果使用文档附加了类型声明,其说明将成为附加说明元素的公开API的一部分.
  2. QQ目标** - 表示适用于注释类型的程序元素类型。 一些可能的值有:TYPE,方法,构造,FIELD等. 如果目标元注释不存在,则注释可用于任何程序元素.
    • ** 继承** - 表示自动继承了注释类型。 如果用户在类声明上查询注释类型,而类声明对此类型没有注释,则该类的超类会自动被查询注释类型. 此进程将重复进行,直到找到该类型的注释,或达到类分级(Object)的上层.
    • 保留** - 说明保留附加说明类型的说明需要多长时间。 它需要保留政策参数,其可能值为SURCE、CLAS和RUNTIME 5。 * ** 可重复** - 用来表示其声明的注释类型可重复。 (_) (英语)

内置在Java中的注释

Java 提供五个内置的注释。

  1. " 超越 " ----当我们想推翻超级阶级方法时,我们应当使用这一注释告知编纂者,我们超越了一种方法。 因此,当超类方法被移除或被更改时,编译器会显示出错误消息. 学习为什么我们应该总是使用 [java 凌驾注 (/community/touristics/java-overried-method-overriding) ,同时使用一个方法.
  2. QQ 折旧 - 当我们想要编译者知道一种方法已经贬值时,我们应该使用这个注释. Java建议,在javadoc中,我们应提供资料,说明为什么这种方法被贬值,以及使用何种替代方法。 () (英语). `Suppress Warnings' - 这只是为了告诉编译者忽略他们制作的具体警告,例如使用[java 通用 [(/community/tourises/java-generics-example-metrode-class-interface)中的原始类型. "Java Controduals Tuarial – 例类,界面,方法,通关卡等等". 它的保留政策是STURCE,被编译器丢弃. ( )4. 功能界面 ' - 在[Java 8](/community/tourics/java-8-features- with-examples)中引入了这种注释,以表示该接口的用意是一个功能接口. () )5. QQSafeVarargs ' - 程序员断言,附加说明的方法或构造器的正体不会在其 varargs 参数上执行潜在的不安全操作. ( (英语)

Java 注释示例

让我们看看一个 Java 示例,展示了 Java 中的内置注释以及我们在上面的示例中创建的自定义注释的使用。

 1package com.journaldev.annotations;
 2
 3import java.io.FileNotFoundException;
 4import java.util.ArrayList;
 5import java.util.List;
 6
 7public class AnnotationExample {
 8
 9    public static void main(String[] args) {
10    }
11
12    @Override
13    @MethodInfo(author = "Pankaj", comments = "Main method", date = "Nov 17 2012", revision = 1)
14    public String toString() {
15    	return "Overriden toString method";
16    }
17
18    @Deprecated
19    @MethodInfo(comments = "deprecated method", date = "Nov 17 2012")
20    public static void oldMethod() {
21    	System.out.println("old method, don't use it.");
22    }
23
24    @SuppressWarnings({ "unchecked", "deprecation" })
25    @MethodInfo(author = "Pankaj", comments = "Main method", date = "Nov 17 2012", revision = 10)
26    public static void genericsTest() throws FileNotFoundException {
27    	List l = new ArrayList();
28    	l.add("abc");
29    	oldMethod();
30    }
31
32}

我认为以上的Java注释示例是自我解释的,并在不同情况下展示了注释的使用。

Java 注释解析

请注意,注释保留策略应该是 RUNTIME,否则其信息将在运行时不可用,我们将无法从中获取任何数据。

 1package com.journaldev.annotations;
 2
 3import java.lang.annotation.Annotation;
 4import java.lang.reflect.Method;
 5
 6public class AnnotationParsing {
 7
 8    public static void main(String[] args) {
 9    	try {
10    		for (Method method : AnnotationParsing.class.getClassLoader()
11    				.loadClass(("com.journaldev.annotations.AnnotationExample")).getMethods()) {
12    			// checks if MethodInfo annotation is present for the method
13    			if (method.isAnnotationPresent(com.journaldev.annotations.MethodInfo.class)) {
14    				try {
15    					// iterates all the annotations available in the method
16    					for (Annotation anno : method.getDeclaredAnnotations()) {
17    						System.out.println("Annotation in Method '" + method + "' : " + anno);
18    					}
19    					MethodInfo methodAnno = method.getAnnotation(MethodInfo.class);
20    					if (methodAnno.revision() == 1) {
21    						System.out.println("Method with revision no 1 = " + method);
22    					}
23
24    				} catch (Throwable ex) {
25    					ex.printStackTrace();
26    				}
27    			}
28    		}
29    	} catch (SecurityException | ClassNotFoundException e) {
30    		e.printStackTrace();
31    	}
32    }
33
34}

上述方案的结果是:

1Annotation in Method 'public java.lang.String com.journaldev.annotations.AnnotationExample.toString()' : @com.journaldev.annotations.MethodInfo(author=Pankaj, revision=1, comments=Main method, date=Nov 17 2012)
2Method with revision no 1 = public java.lang.String com.journaldev.annotations.AnnotationExample.toString()
3Annotation in Method 'public static void com.journaldev.annotations.AnnotationExample.oldMethod()' : @java.lang.Deprecated()
4Annotation in Method 'public static void com.journaldev.annotations.AnnotationExample.oldMethod()' : @com.journaldev.annotations.MethodInfo(author=Pankaj, revision=1, comments=deprecated method, date=Nov 17 2012)
5Method with revision no 1 = public static void com.journaldev.annotations.AnnotationExample.oldMethod()
6Annotation in Method 'public static void com.journaldev.annotations.AnnotationExample.genericsTest() throws java.io.FileNotFoundException' : @com.journaldev.annotations.MethodInfo(author=Pankaj, revision=10, comments=Main method, date=Nov 17 2012)

反射 API 非常强大,广泛用于 Java, J2EE 框架,如 Spring, Hibernate, JUnit,请查看 Reflection in Java

Servlet Specs 3.0 引入了用于 Servlet 配置和 init 参数的注释的使用,请参阅 Java Servlet Tutorial 2.我们可以使用 Struts 2 中的注释来配置其动作类和结果页,请参阅 [Struts 2 Hello World Annotation Example](/community/tutorials/struts-2-hello-world-example-with-annotations-and-without-struts-xml file "Struts 2 Hello World Example with Annotations and without struts.xml file")

参考: Oracle 网站

Published At
Categories with 技术
Tagged with
comments powered by Disqus