java annotation

java annotation 是java5之后引入的。主要包括三种标准注解:

@Override:覆盖超类中的方法。

@Deprecated:表示不推荐,可以用来表示一些将要在未来版本被废弃的方法。

@SuppressWarnings:关闭不当的编译器表示信息。

 

除了三种标准注解外,还有四种元注解。

@Target 表示注解的作用范围。可能的ElementType包括:CONSTRUCTOR(构造器的声明),FIELD(域声明),LOCAL_VARIABLE(局部变量的声明)、METHOD(方法声明)。PAKAGE(包声明)、PARAMETER(参数声明)、TYPE(类、接口、注解或者是Enum的声明)。其中相对来说Method和field更常用。

 

@Retention: 表示注解保存的级别。可选的RetentionPolicy包括: SOURCE(注解将被编译器丢掉,也就是class文件中不存在),CLASS(注解在class文件中可用,但会被vm丢掉),RUNTIME(VM在运行其也将保留这些注解,可以通过反射读取注解的信息)。

 

@Documented 将注解包含在javadoc中。

@Inherited 允许子类继承父类的注解。

 

下面看一个annotation的示例:

Annotation的定义:

package annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationDemo {
	
	String check() default "hello world!";
}

 

Annotation的处理器:

package annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class AnnotationDemoInterceptor {

	public void checkInterceptor(Class<?>cl){
		for(Method m :cl.getDeclaredMethods()){
			 AnnotationDemo annoDemo = m.getAnnotation(AnnotationDemo.class);
			 if(annoDemo !=null){
				 System.out.println("Found AnnotationDemo in "+m.getName()+" :"+annoDemo.check());
			 }else{
				 System.out.println("Found nothing in "+m.getName()); 
			 }
		}
	}
}
 

测试类:

package annotation;

public class AnnotationDemoTest {

	public static void main(String[]args){
		AnnotationDemoInterceptor adi = new AnnotationDemoInterceptor();
		adi.checkInterceptor(AnnotationDemoTest.class);
	}
	@AnnotationDemo(check = "hello, shuofenglxy")
	public static void doSomething(){
		System.out.println("This is an annotation example!");
	}
	@AnnotationDemo()
	public static void doHello(){
		System.out.println("This is an annotation example!");
	}
	public static void doOtherthing(){
		System.out.println("This is normal method!");
	}
}
 

测试结果:

Found AnnotationDemo in doSomething :hello, shuofenglxy
Found AnnotationDemo in doHello :hello world!
Found nothing in doOtherthing
Found nothing in main

 

说明:通过这个简单的示例,大概说明了自己书写annotation的过程,在spring,ejb中大量应用了annotation,原理也是大致相同的,无非定义annotation,设置处理器,然后就可以用了。在自己的应用中可以用annotation的方式来做权限管理等等。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值