Java Annotation

  Spring MVC中存在大量的注解,@RequestMapping可方便实现路由跳转,下面我们看看注解是怎么实现的。

 一. 定义注释

import java.lang.annotation.*;

/**
 * Annotation Interface class 
 * @author sunling3
 *
 */
@Retention(RetentionPolicy.RUNTIME)	// 注释运行时依然存在
@Target(ElementType.METHOD)				// 注释用于方法
public @interface HelloAnnotation {
	String paramValue() default "Kettas";		// 参数及默认值
}

 

  反编译:

public abstract @interface com/sun/annotation/HelloAnnotation implements java/lang/annotation/Annotation 
public abstract paramValue()Ljava/lang/String;
default="Kettas"

 

 查看字节码发现HelloAnnotation实际上是继承Annotation,paramValue为abstract类型。

二. 使用注释

public class HelloElement {
	// 普通方法
	public void sayHello( String name ){
		System.out.println( "Hello " + name );
	}

	// 注释使用默认参数
	@HelloAnnotation
	public void sayHelloWithDefault( String name ){
		System.out.println( "Hello " + name );
	}

	// 注释传入参数
	@HelloAnnotation( paramValue="Jack")
	public void sayHelloWithAnnotation( String name ){
		System.out.println( "Hello " + name );
	}
}

 

三. 测试 

public class AnnotationTest {
	public static void main(String[] args)  throws Exception {
		HelloElement element = new HelloElement();
		
		// 反射获取方法
		Method[] methods = HelloElement.class.getDeclaredMethods();
		HelloAnnotation pAnnotation = null;
		
		for( Method method : methods ){
			System.out.println( "Method: " + method.getName() );
			
			// 反射获取注释
			if( (pAnnotation = method.getAnnotation(HelloAnnotation.class)) != null ){
				// 注释获取值
				method.invoke( element, pAnnotation.paramValue() );
			}else{
				// 普通调用
				method.invoke( element, "Sun" );
			}
		}
	}
}

 

 上述代码通过反射方式获取注解值,执行结果如下:

Method: sayHelloWithDefault
Hello Kettas
Method: sayHelloWithAnnotation
Hello Jack
Method: sayHello
Hello Sun

 

 参考文章

  1.  Java注解机制
  2.  Spring MVC注解实现原理

 

猜你喜欢

转载自tcspecial.iteye.com/blog/2387818
今日推荐