java annotation_java annotation

java annotation

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 comments provide information about the code. Java annotations have no direct effect on the code they annotate. In the Java annotation tutorial, we will study the following;

  1. Built-in Java annotations

    Built-in Java annotations
  2. How to write Custom Annotation

    How to write custom annotations
  3. Annotations usage and how to parse annotations using Reflection API.

    The usage of annotations and how to parse annotations using the Reflection API .

Java Annotations ( Java Annotations )

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

Java 1.5 introduced annotations and it is now 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.

Java annotations are metadata about the program embedded in the program itself. It can be parsed by annotation parsing tools or compilers. We can also specify annotation availability to compile time only or until 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.

Before Java annotations were used, program metadata was available through Java annotations or Javadoc, but annotations provided more functionality. Annotation metadata is also available at runtime, which can be used by the annotation parser to determine 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.

例如,在Jersey网络服务中,我们将带有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 java override annotation while overriding a method.

    @Override –当我们要重写超类的方法时,应使用此批注通知编译器我们正在重写方法。 因此,当删除或更改超类方法时,编译器将显示错误消息。 了解为什么我们在覆盖方法时总是应该使用Java覆盖注释
  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 java generics. It’s retention policy is SOURCE and it gets discarded by compiler.

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

    @FunctionalInterfaceJava 8中引入了此批注,以指示该接口旨在用作功能接口
  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, Hibernate, JUnit, check out Reflection in Java.

Reflection API非常强大,并且在Java,Spring, Hibernate ,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 Java Servlet Tutorial.

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

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

Reference: Oracle website

参考: Oracle网站

翻译自: https://www.journaldev.com/721/java-annotations

java注解

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324133610&siteId=291194637