Java 自定义注解

  1. Java经过关键字@interface实现自定义注解
  2. Java经过元注解来约束其它注解。元注解即注解的注解。元注解包括四个:
  • @Target.指示注解类型所适用的程序元素的种类。
  • @Retention.指示注解类型的注解要保留多久。RetentionPolicy包含3个值:
            
CLASS
编译器将注解记录在类文件中,但在运行时VM不须要保留注解。默认是此策略。
RUNTIME 编译器将注解记录在类文件中,在运行时VM中保留,所以能够经过反射读取。
SOURCE 编译器会丢弃。
  • @Documented.指示某一类型的注解将经过javadoc和相似的默认工具进行文档化。
  • @Inherited.指示该注解类型将被继承。

    3.  自定义注解实例 java

        注解的定义: 工具

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.FIELD)
public @interface UColumn {

	public int precision() default 8;
	public int length() default 255;
	public String name() default "";
}



        注解的使用:

public class Student {

	@UColumn(name="id",precision=5)
	private Integer id;
	
	@UColumn(name="name",length=64)
	private String name;
	
	@UColumn(name="age",precision=3)
	private Integer age;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

}



        经过反射获取注解信息:

public static void main(String[] args) throws Exception{
		Student stu=new Student();
		stu.setId(123456);
		stu.setName("stack");
		stu.setAge(1000);
		
		Class<?> clazz=stu.getClass();
		Field[] fields=clazz.getDeclaredFields();
		if(fields.length>0){
			for(Field field:fields){
				Annotation[] annotations=field.getAnnotations();
				if(annotations.length<=0)continue;
				
				Class<?> type=field.getType();
				for(Annotation annotation:annotations){
					if(annotation.annotationType().equals(UColumn.class)){
						UColumn col=field.getAnnotation(UColumn.class);
						if(type.equals(String.class)){
							int length=col.length();
							if(field.get(stu).toString().length()>length){
								System.out.println(field.getName()+" length error!");
							}
						}else if(type.equals(Integer.class)){
							int precision=col.precision();
							if(field.get(stu).toString().length()>precision){
								System.out.println(field.getName()+" length error!");
							}
						}
					}
						
				}
					
			}
		}
	}
相关文章
相关标签/搜索