`

Java自定义Annotation学习1

阅读更多
  • 本次学习的目标是为了获取如下Java类成员中ID的值:
  • package com.perficient.annotation;
    
    public class WebPage {
    	
    	@Identifier(id= "A")
    	public String buttonA;
    	
    	@Identifier(id= "B")
    	public String buttonB;
    
    }
    

  • 创建自定义的Annotation:
  • package com.perficient.annotation;
    
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    
    @Target(ElementType.FIELD) 
    @Retention(RetentionPolicy.RUNTIME)    
    public @interface Identifier {
    	
    	public String id();
    	
    }
    


    注意:Target一定要给予正确的值,如果是类成员的话用Field,是方法要用Method
  • 编写测试类
  • package com.perficient.annotation;
    
    import java.lang.reflect.Field;
    
    public class AnnotationTest {
    	public static void main(String[] args) throws ClassNotFoundException {
    		String className = "com.perficient.annotation.WebPage";
    		Class<?> test = Class.forName(className);
    		Field[] fields = test.getFields();
    		for (Field field : fields){
    			System.out.println("The field Name is:" + field);
    			boolean flag = field.isAnnotationPresent(Identifier.class);
    			if (flag) {
    				Identifier idt = (Identifier) field
    						.getAnnotation(Identifier.class);
    				System.out.println("Id is:" + idt.id());
    			} else {
    				System.out.println("The annotation can't be found");
    			}						
    		}		
    	}
    }
    


    注意:如果是Method,需要使用getDeclaredMethods(),如果用getMethods()不会返回我们所需要的结果
  • 输出结果:
  • The field Name is:public java.lang.String com.perficient.annotation.WebPage.buttonA
    Id is:A
    The field Name is:public java.lang.String com.perficient.annotation.WebPage.buttonB
    Id is:B
    

    1
    1
    分享到:
    评论

    相关推荐

    Global site tag (gtag.js) - Google Analytics