使用注解的小实例

  @interface用来声明一个注解,其中的每一个方法实际上是声明了一个配置参数。方法的名称就是参数的名称,返回值类型就是参数的类型(返回值类型只能是基本类型、Class、String、enum)。可以通过default来声明参数的默认值。


下面是实际的例子  结合反射进行注解的开发。
1.注解类
    package com.yucheng.cmis.dao.test;
    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 SayHiAnnotation {
	    String paramValue() default "johness"; // 表示我的注解需要一个参数 名        为"paramValue" 默认值为"johness"
	    int id() default 1;
    }

2.使用的注解类

    package com.yucheng.cmis.dao.test;

    public class UserAnnotation {
	     // 普通的方法
	        public void SayHiDefault(String name){
	            System.out.println("Hi, " + name);
	        }
	       // 使用注解并传入参数的方法
	        @SayHiAnnotation(paramValue="Jack")
	        public void SayHiAnnotation(String name){
	            System.out.println("Hi, " + name);
	       }
	        // 使用注解并使用默认参数的方法
	       @SayHiAnnotation
	        public void SayHiAnnotationDefault(String name){
	            System.out.println("Hi, " + name);
	        }
    }

3.测试类


package com.yucheng.cmis.dao.test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class AnnotationTest {
	public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException{
		UserAnnotation element = new UserAnnotation(); // 初始化一个实例,用于方法调用
		        Method[] methods = UserAnnotation.class.getDeclaredMethods(); // 获得所有方法   
		        for (Method method : methods) {
		             SayHiAnnotation annotationTmp = null;
		            if((annotationTmp = method.getAnnotation(SayHiAnnotation.class))!=null) // 检测是否使用了我们的注解
		                 method.invoke(element,annotationTmp.paramValue()); // 如果使用了我们的注解,我们就把注解里的"paramValue"参数值作为方法参数来调用方法
		            else
		                method.invoke(element, "Rose"); // 如果没有使用我们的注解,我们就需要使用普通的方式来调用方法了
		         }
	}
}

猜你喜欢

转载自blog.csdn.net/bestxianfeng163/article/details/81217542