Java注解教程和自定义注解

Java注解提供关于代码的信息,并且对它们注解的代码没有直接的影响。在这篇教程中,我们将学习Java注解,如何自定义注解,注解用法和如何使用反射解析注解。

Java注解在Java1.5被引用并且在一些Java框架如Hibernate,Jersey,Spring中被广泛使用。注解是被嵌入到程序自身中的程序的元数据。它可以被注解解析工具或编译器解析。我们也可以指定注解的生命周期,或者仅在编译期间可用或者直到运行时。

在引入注解之前,我们可以通过程序注释或者Java文档来获取程序的元数据,但是注解提供的更多。它不仅包含元数据而且它能决定自身是否可用而且注解解析器可以使用它来控制处理流。

在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();
}

注解方法不能有参数。

注解方法的返回值类型限于基本类型,String,Enums,Annotation或者上面这些的组合。

注解方法可以有默认值。

注解可以附加元数据。元注解可以提供关于这个注解的信息。

四种元注解:

[email protected] 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.

[email protected] – 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.

[email protected] – 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.

[email protected] – indicates how long annotations with the annotated type are to be retained. It takes RetentionPolicy argument whose Possible values are SOURCE, CLASS and RUNTIME

Java内置注解

Java提供三个内置注解:

[email protected]当我们要重写父类的一个方法时,我们应该使用这个注解告诉编译器我们重写了这个方法。因此当父类的这个方法被移除或发生改变时,编译器将报错。

[email protected]当我们想让编译器知道一个方法已经过时时,我们应该这个注解。Java推荐将这个方法过时的原因以及它的替代方案写在Java文档中。

[email protected]这个仅是用来告诉编译器忽略产生的特定警告,比如在泛型中使用原始类型。它的retention策略是SOURCE,所以它将被编译器丢弃。

让我们看一个使用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();
	}

}

我相信这个例子大家都能够看的懂,它向我们展示了在不同情境下注解的使用。

Java注解解析

我们将使用反射从一个类中解析主解。请注意注解的Retention策略必须是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();
		}
	}

}

上面程序的输出为:

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)
时间: 2024-08-01 10:40:59

Java注解教程和自定义注解的相关文章

Java注解教程及自定义注解

Java注解提供了关于代码的一些信息,但并不直接作用于它所注解的代码内容.在这个教程当中,我们将学习Java的注解,如何定制注解,注解的使用以及如何通过反射解析注解. Java1.5引入了注解,当前许多java框架中大量使用注解,如Hibernate.Jersey.Spring.注解作为程序的元数据嵌入到程序当中.注解可以被一些解析工具或者是编译工具进行解析.我们也可以声明注解在编译过程或执行时产生作用. 在使用注解之前,程序源数据只是通过java注释和javadoc,但是注解提供的功能要远远超

Java注解教程:自定义注解示例,利用反射进行解析

Java注解能够提供代码的相关信息,同时对于所注解的代码结构又没有直接影响.在这篇教程中,我们将学习Java注解,如何编写自定义注解,注解的使用,以及如何使用反射解析注解. 注解是Java 1.5引入的,目前已被广泛应用于各种Java框架,如Hibernate,Jersey,Spring.注解相当于是一种嵌入在程序中的元数据,可以使用注解解析工具或编译器对其进行解析,也可以指定注解在编译期或运行期有效. 在注解诞生之前,程序的元数据存在的形式仅限于java注释或javadoc,但注解可以提供更多

深入JAVA注解(Annotation):自定义注解 (转)

原文出自:http://blog.csdn.net/yjclsx/article/details/52101922 一.基础知识:元注解 要深入学习注解,我们就必须能定义自己的注解,并使用注解,在定义自己的注解之前,我们就必须要了解Java为我们提供的元注解和相关定义注解的语法. 元注解: 元注解的作用就是负责注解其他注解.Java5.0定义了4个标准的meta-annotation类型,它们被用来提供对其它 annotation类型作说明.Java5.0定义的元注解: [email prote

【java开发系列】—— 自定义注解(转)

之前在开发中,就总纳闷,为什么继承接口时,会出现@Override注解,有时候还会提示写注解@SuppressWarnings? 原来这是java特有的特性,注解! 那么什么是注解呢? 注解就是某种注解类型的一个实例,我们可以用它在某个类上进行标注,这样编译器在编译我们的文件时,会根据我们自己设定的方法来编译类. 注解都是什么呢?看下面这张图就明白了! 上面的图可以看出,注解大体上分为三种:标记注解,一般注解,元注解 这里面Override这个没测试出来,因为目前的Eclipse会自动帮我们排错

java基础知识:自定义注解

转自 深入了解注解 要深入学习注解,我们就必须能定义自己的注解,并使用注解,在定义自己的注解之前,我们就必须要了解Java为我们提供的元注解和相关定义注解的语法. 元注解的作用就是负责注解其他注解.Java5.0定义了4个标准的meta-annotation类型,它们被用来提供对其它 annotation类型作说明.Java5.0定义的元注解: [email protected], [email protected], [email protected], [email protected] 这

java 注解分析及自定义注解

注解概念: java提供了一种原程序中的元素关联任何信息和任何元数据的途径与方法. 注解分类: 运行机制分类:源码注解,编译时注解,运行时注解. 来源分类:JDK的注解,第三方注解,自定义注解. 自定义注解语法要求: import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Inherited;import java.lang.annotat

java 注解学习(一、注解入门,自定义注解)

注解是在我们的代码中添加信息提供了一种更加简便的方法,通过注解,我们可以在适当的时候非常方便的使用一些数据.具体的注解的概念就不展开了,具体通过一个例子来说明自定义注解的使用. 具体的场景是,我们开了一家超市,超市里面有个自动货柜机,货柜机上的产品都有产品编号.价格.产品描述和注意事项,超市管理人员需要在自动售卖机卖出东西时,实时的进行记录,通过注解再进行售卖的时候进行相关信息的记录,为了实现这个目标,我们首先申明一个注解,如下: @Target(ElementType.METHOD) @Ret

【java开发系列】—— 自定义注解

之前在开发中,就总纳闷,为什么继承接口时,会出现@Override注解,有时候还会提示写注解@SuppressWarnings? 原来这是java特有的特性,注解! 那么什么是注解呢? 注解就是某种注解类型的一个实例,我们可以用它在某个类上进行标注,这样编译器在编译我们的文件时,会根据我们自己设定的方法来编译类. 注解都是什么呢?看下面这张图就明白了! 上面的图可以看出,注解大体上分为三种:标记注解,一般注解,元注解 这里面Override这个没测试出来,因为目前的Eclipse会自动帮我们排错

java注解annotation,自定义注解

定义: package com.dxz.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; //定义注解 @Target({ ElementType.TYPE, ElementType.FIELD, Ele