zoukankan      html  css  js  c++  java
  • Java Annotation,Java注解

    Annotation

    Annotaions (also known as metadata) provide a formalized way to add information to yourcode so that you can easily use that data at some later point.
    Defining annotationsHere is the definition of the annotation above. You can see that annotation definitions look a lot like interface definitions.

    In fact, they compile to class files like any other Java interface:Apart from the @ symbol, the definition of @Test is much like that of an empty interface.

    An annotation definition also requires the meta-annotations @Target and @Retention.

    @Target defines where you can apply this annotation(a method or a field, for example).

    @Retention defines whether the annotations are availablein the (SOURCE), in the classfiles (CLASS), or at run time(RUNTIME).

    e.g.:

    //UseCase.java
    
    package annotationtest;
    
    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 UseCase {
    	public int id();
    	public String description() default "没有描述";
    }
    
    //PasswordUtils.java
    
    package annotationtest;
    
    public class PasswordUtils {
    
    	@UseCase(id=1, description="validate 密码")
    	public boolean validatePassword(String password){
    		return true;
    	}
    	@UseCase(id=2, description="encrypt 密码")
    	public boolean encryptPassword(String password){
    		return true;
    	}
    	@UseCase(id=3, description="checkfor 密码")
    	public boolean checkforPassword(String password){
    		return true;
    	}	
    	
    }
    //Test.java
    
    package annotationtest;
    
    import java.lang.reflect.Method;
    
    public class Test {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		
    		Method[] methods = PasswordUtils.class.getDeclaredMethods();
    
    		for (Method m : methods) {
    			UseCase uc= m.getAnnotation(UseCase.class);
    			System.out.println("id=" + uc.id()+",description="+uc.description());
    		}
    		
    	}
    
    }
    
    // from : thinking in java.
    

  • 相关阅读:
    vs2019编译错误:Exception Processing Message 0xc0000005 Parameters...
    error LNK2001
    Debug Assertion Failed
    对路径“………………”的访问被拒绝
    c语言打开文件为什么总是以二进制方式打开
    关于typedef的用法总结
    xml学习第一天
    关于VS2017编译成功系统找不到指定文件.exe的问题
    引入的外部js文件在html文件在浏览器中乱码显示
    结对作业(四则运算)
  • 原文地址:https://www.cnblogs.com/wucg/p/1987842.html
Copyright © 2011-2022 走看看