博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java注解_Java注解
阅读量:2528 次
发布时间:2019-05-11

本文共 10379 字,大约阅读时间需要 34 分钟。

java注解

Java Annotations provides information about the code. Java annotations have no direct effect on the code they annotate. In java annotations tutorial, we will look into the following;

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

  1. Built-in Java annotations

    内置Java注释
  2. How to write Custom Annotation

    如何编写自定义注释
  3. Annotations usage and how to parse annotations using .

    批注的用法以及如何使用解析批注。

Java注解 (Java Annotations)

Java 1.5 introduced annotations and now it’s heavily used in Java EE frameworks like Hibernate, , and .

Java 1.5引入了注释,现在它已在Hibernate, 和等Java EE框架中大量使用。

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.

Java注释是有关嵌入在程序本身中的程序的元数据。 可以通过注释解析工具或编译器进行解析。 我们还可以指定注释可用性以仅编译时间或直到运行时。

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.

在使用Java注释之前,程序元数据可通过Java注释或Javadoc获得,但注释提供的功能更多。 注释元数据也可以在运行时使用,注释解析器可以使用它来确定流程。

For example, in 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.

例如,在我们将带有URI字符串的PATH注释添加到方法中,并且在运行时,jersey对其进行解析,以确定要为给定URI模式调用的方法。

Java自定义注释 (Java Custom Annotation)

Creating custom annotation is similar to writing an interface, except that the interface keyword is prefixed with @ symbol. We can declare methods in annotation.

创建自定义批注与编写接口相似,不同之处在于interface关键字的前缀是@符号。 我们可以在注解中声明方法。

Let’s see java custom annotation example and then we will discuss its features and important points.

让我们看一下Java自定义注释示例,然后我们将讨论其功能和要点。

package com.journaldev.annotations;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Inherited;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Documented@Target(ElementType.METHOD)@Inherited@Retention(RetentionPolicy.RUNTIME)public @interface MethodInfo{	String author() default "Pankaj";	String date();	int revision() default 1;	String comments();}

Some important points about java annotations are:

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

  1. Annotation methods can’t have parameters.

    注释方法不能有参数。
  2. Annotation methods return types are limited to primitives, String, Enums, Annotation or array of these.

    注释方法的返回类型仅限于原语,字符串,枚举,注释或它们的数组。
  3. Java Annotation methods can have default values.

    Java注释方法可以具有默认值。
  4. Annotations can have meta annotations attached to them. Meta annotations are used to provide information about the annotation.

    批注可以附加元批注。 元注释用于提供有关注释的信息。

Java中的元注释 (Meta annotations in java)

There are five types of meta annotations:

元注释有五种类型:

  1. @Documented – indicates that elements using this annotation should be documented by javadoc and similar tools. This type should be used to annotate the declarations of types whose annotations affect the use of annotated elements by their clients. If a type declaration is annotated with Documented, its annotations become part of the public API of the annotated elements.

    @Documented –表示使用此注释的元素应由javadoc和类似工具记录。 此类型应用于注释类型的声明,这些类型的注释会影响其客户端对已注释元素的使用。 如果类型声明用Documented进行注释,则其注释将成为带注释元素的公共API的一部分。
  2. @Target – indicates the kinds of program element to which an annotation type is applicable. Some possible values are TYPE, METHOD, CONSTRUCTOR, FIELD etc. If Target meta-annotation is not present, then annotation can be used on any program element.

    @Target –指示注释类型适用的程序元素的种类。 一些可能的值是TYPE,METHOD,CONSTRUCTOR,FIELD等。如果没有Target元注释,则可以在任何程序元素上使用注释。
  3. @Inherited – indicates that an annotation type is automatically inherited. If user queries the annotation type on a class declaration, and the class declaration has no annotation for this type, then the class’s superclass will automatically be queried for the annotation type. This process will be repeated until an annotation for this type is found, or the top of the class hierarchy (Object) is reached.

    @Inherited –表示注释类型是自动继承的。 如果用户在类声明中查询注释类型,并且该类声明没有该类型的注释,则将自动查询该类的超类以获取注释类型。 重复此过程,直到找到该类型的注释,或到达类层次结构(对象)的顶部为止。
  4. @Retention – indicates how long annotations with the annotated type are to be retained. It takes RetentionPolicy argument whose Possible values are SOURCE, CLASS and RUNTIME

    @Retention –指示带注释类型的注释将保留多长时间。 它采用RetentionPolicy参数,其可能值为SOURCE,CLASS和RUNTIME
  5. @Repeatable – used to indicate that the annotation type whose declaration it annotates is repeatable.

    @Repeatable –用于指示其注释的注释类型是可重复的。

Java内置注释 (Built-in annotations in Java)

Java Provides five built-in annotations.

Java提供五个内置注释。

  1. @Override – When we want to override a method of Superclass, we should use this annotation to inform compiler that we are overriding a method. So when superclass method is removed or changed, compiler will show error message. Learn why we should always use while overriding a method.

    @Override –当我们要重写超类的方法时,应使用此批注通知编译器我们正在重写方法。 因此,当删除或更改超类方法时,编译器将显示错误消息。 了解为什么我们在覆盖方法时总是应该使用 。
  2. @Deprecated – when we want the compiler to know that a method is deprecated, we should use this annotation. Java recommends that in javadoc, we should provide information for why this method is deprecated and what is the alternative to use.

    @Deprecated –当我们希望编译器知道某个方法已被弃用时,应使用此注释。 Java建议在javadoc中,我们应提供有关为什么不赞成使用此方法以及可以使用什么替代方法的信息。
  3. @SuppressWarnings – This is just to tell compiler to ignore specific warnings they produce, for example using raw types in . It’s retention policy is SOURCE and it gets discarded by compiler.

    @SuppressWarnings –这只是告诉编译器忽略它们产生的特定警告,例如使用原始类型。 它的保留策略是SOURCE,并且被编译器丢弃。
  4. @FunctionalInterface – This annotation was introduced in to indicate that the interface is intended to be a .

    @FunctionalInterface – 中引入了此批注,以指示该接口旨在用作 。
  5. @SafeVarargs – A programmer assertion that the body of the annotated method or constructor does not perform potentially unsafe operations on its varargs parameter.

    @SafeVarargs –程序员断言带注释的方法或构造函数的主体不会对其varargs参数执行潜在的不安全操作。

Java注释示例 (Java Annotations Example)

Let’s see a java example showing the use of built-in annotations in java as well as the use of custom annotation created by us in the above example.

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

package com.journaldev.annotations;import java.io.FileNotFoundException;import java.util.ArrayList;import java.util.List;public class AnnotationExample {	public static void main(String[] args) {	}	@Override	@MethodInfo(author = "Pankaj", comments = "Main method", date = "Nov 17 2012", revision = 1)	public String toString() {		return "Overriden toString method";	}	@Deprecated	@MethodInfo(comments = "deprecated method", date = "Nov 17 2012")	public static void oldMethod() {		System.out.println("old method, don't use it.");	}	@SuppressWarnings({ "unchecked", "deprecation" })	@MethodInfo(author = "Pankaj", comments = "Main method", date = "Nov 17 2012", revision = 10)	public static void genericsTest() throws FileNotFoundException {		List l = new ArrayList();		l.add("abc");		oldMethod();	}}

I believe above java annotation example is self-explanatory and showing the use of annotations in different cases.

我相信上面的Java注释示例是不言自明的,并显示了在不同情况下使用注释的情况。

Java注解解析 (Java Annotations Parsing)

We will use Reflection to parse java annotations from a class. Please note that Annotation Retention Policy should be RUNTIME otherwise its information will not be available at runtime and we won’t be able to fetch any data from it.

我们将使用Reflection来解析类中的Java批注。 请注意,注释保留策略应为RUNTIME,否则其信息将在运行时不可用,我们将无法从中获取任何数据。

package com.journaldev.annotations;import java.lang.annotation.Annotation;import java.lang.reflect.Method;public class AnnotationParsing {	public static void main(String[] args) {		try {			for (Method method : AnnotationParsing.class.getClassLoader()					.loadClass(("com.journaldev.annotations.AnnotationExample")).getMethods()) {				// checks if MethodInfo annotation is present for the method				if (method.isAnnotationPresent(com.journaldev.annotations.MethodInfo.class)) {					try {						// iterates all the annotations available in the method						for (Annotation anno : method.getDeclaredAnnotations()) {							System.out.println("Annotation in Method '" + method + "' : " + anno);						}						MethodInfo methodAnno = method.getAnnotation(MethodInfo.class);						if (methodAnno.revision() == 1) {							System.out.println("Method with revision no 1 = " + method);						}					} catch (Throwable ex) {						ex.printStackTrace();					}				}			}		} catch (SecurityException | ClassNotFoundException e) {			e.printStackTrace();		}	}}

Output of the above program is:

上面程序的输出是:

Annotation 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)Method with revision no 1 = public java.lang.String com.journaldev.annotations.AnnotationExample.toString()Annotation in Method 'public static void com.journaldev.annotations.AnnotationExample.oldMethod()' : @java.lang.Deprecated()Annotation 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)Method with revision no 1 = public static void com.journaldev.annotations.AnnotationExample.oldMethod()Annotation 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)

Reflection API is very powerful and used widely in Java, J2EE frameworks like Spring, , JUnit, check out .

Reflection API非常强大,并且在Java,Spring, ,JUnit等J2EE框架中得到了广泛使用,并在Java中签出了

That’s all for the java annotations example tutorial, I hope you learned something from it.

这就是Java注释示例教程的全部内容,希望您从中学到一些东西。

Java Annotations Updates:

Java注释更新

  1. Servlet Specs 3.0 introduced use of annotations for Servlet Configuration and init parameters, read more at .

    Servlet Specs 3.0引入了对Servlet Configuration和init参数使用注释的信息,有关更多信息,请
  2. We can use annotations in Struts 2 to configure it’s action classes and result pages, check working example at .

    我们可以在Struts 2中使用注释来配置它的动作类和结果页面,请在查看工作示例。

Reference:

参考:

翻译自:

java注解

转载地址:http://eaozd.baihongyu.com/

你可能感兴趣的文章
PHP批量插入
查看>>
laravel连接sql server 2008
查看>>
Ubuntu菜鸟入门(五)—— 一些编程相关工具
查看>>
valgrind检测linux程序内存泄露
查看>>
Hadoop以及组件介绍
查看>>
1020 Tree Traversals (25)(25 point(s))
查看>>
第一次作业
查看>>
“==”运算符与equals()
查看>>
单工、半双工和全双工的定义
查看>>
Hdu【线段树】基础题.cpp
查看>>
时钟系统
查看>>
BiTree
查看>>
5个基于HTML5的加载动画推荐
查看>>
水平权限漏洞的修复方案
查看>>
静态链接与动态链接的区别
查看>>
Android 关于悬浮窗权限的问题
查看>>
如何使用mysql
查看>>
linux下wc命令详解
查看>>
敏捷开发中软件测试团队的职责和产出是什么?
查看>>
在mvc3中使用ffmpeg对上传视频进行截图和转换格式
查看>>