java annotation

1. java annotation是什么?有什么作用?

       自从java 1.5(代号tiger,1.6代号为mustang)引入annotation以后,java annontation就被广泛的使用了,很多java框架也紧跟潮流,例如Junit、Struts、Spring等流行工具框架中均广泛使用了annontion。 Spring 2.5提供了完全基于注释配置 Bean、装配 Bean 的功能,您可以使用基于注释的 Spring IoC 替换原来基于 XML 的配置.  

       Annotation语法,除了@符号的使用外,它基本上与java的固有语法一致,java内置了三种注解,定义在java.lang.annotation包。

       Annotation可以被编译为近class文件的,也可以在运行时被虚拟机获得,从而影响运行时行为。 

      Annotation一般作为一种辅助途径,应用在软件框架或工具中,在这些工具类中根据不同的 annontation注解信息采取不同的处理过程或改变相应程序元素(类、方法及成员变量等)的行为

2.如何自定义annotation?

     

自定义annotation

package annotation;

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
	public String value() default "hello annotation";

}

测试annotation

package annotation;

import java.lang.reflect.Method;

public class TestAnno {

   @MyAnnotation(value = "I am annotation for method_1")	
   public static void method_1(){
	   System.out.println("I am method_1");
   }
   
   @MyAnnotation()	
   public static void method_2(){
	   System.out.println("I am method_2");
   }
	
	public static void main(String[] args) {
		
        method_1();
        method_2();
        
      // 利用反射机制得到方法的annotation  
	  Method[] methods = TestAnno.class.getDeclaredMethods();
	   
	   for(Method method : methods ){

		  boolean hasAnnotation = method.isAnnotationPresent(MyAnnotation.class);
		 
		  if(hasAnnotation){
			  
			  MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
			  System.out.println("metod: " + method.getName() + " ; annotation content: " + annotation.toString() + " annotation value:" + annotation.value());
		  }
	   }   
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值