From jdk5 start, the Java adds support for metadata, that is, Annotation , Annotation is actually a special mark on the code, these tags can be read at the time of compilation, load and run the class, and execute accordingly. Of course, just said, Annotation is just a mark, so if do not have these tags in the code which is able to complete the work, but sometimes with annotations to simplify a lot of code, looks very simple.
Common Annotations ( Annotation )
@Override - defining override inherited methods
@Deprecated - marked obsolete
@SuppressWarning - suppress compiler warnings
JAVA meta-annotation
In addition to the above comments, there is a meta-annotation. Meta-annotation refers to the annotated notes, including @Retention @Target @Document @Inherited four.
1. @ Retention This is the decision you Annotation survival time, it contains a RetationPolicy the value member variable is used to specify that it modifies Annotation retention time, generally :
Retationpolicy.CLASS 1. : compiler will comment recorded in the Class file,
But when java program execution, the JVM will abandon it. But when java program execution, the JVM will abandon it.
2. Retationpolicy.SOURCE: default retention policy annotations in the class exists byte code file, but the runtime not available.
Retationpolicy.RUNTIME 4. : In Retationpolicy.CLASS based on, the JVM implementation of the time will not abandon it, so we generally in the program can be obtained by reflecting this comment, and then processed.
It must first clear the length of the life cycle of the SOURCE <the CLASS <RUNTIME , so MT4 download tutorial former can effect where the latter must also be able to effect. In general, when required to obtain the dynamic annotation information at runtime, the bird can RUNTIME annotation; to some pre-processing operations at compile time, generating a number of such ancillary code (e.g. ButterKnife ), to use CLASS annotation; if only do some checking of operations, such as @Override and @SuppressWarnings , you can choose SOURCE comment.
2. @ Target This annotation is generally used to specify which elements are modified annotated modified as follows:
ElementType.ANNOTATION_TYPE: // comment
ElementType.CONSTRUCTOR: // constructor
ElementType.FIELD: // field, enumeration constants
ElementType.LOCAL_VARIABLE: // local variables
ElementType.METHOD: // method
ElementType.PACKAGE: //包
ElementType.PARAMETER: // method parameters
ElementType.TYPE: // interfaces, classes, enumerations, annotations
@Document this comment modified Annotation classes can be javadoc extraction tool to document
@Inherited he modified notes are inherited, indicating that a subclass can inherit the parent class notes
example
Custom annotation MyClassAnnotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyClassAnnotation {
String value();
}
Custom annotation MyFieldAnnotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyFieldAnnotation {
public String name() default "fieldName";
}
Custom annotation MyMethodAnnotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyMethodAnnotation {
String name();
int age();
}
In instances TestRuntimeAnnotation test case notes:
@MyClassAnnotation(value = "test Class")
public class TestRuntimeAnnotation {
@MyFieldAnnotation
public String fieldInfo = "FiledInfo";
@MyMethodAnnotation(age = 0, name = "zhangsan")
public static String getMethodInfo() {
return TestRuntimeAnnotation.class.getSimpleName();
}
public static void main(String[]args) {
StringBuffer sb = new StringBuffer();
Class<?> cls = TestRuntimeAnnotation.class;
sb.append("Class注解:").append("\n");
MyClassAnnotation myClassAnnotation = cls.getAnnotation(MyClassAnnotation.class);
if (myClassAnnotation != null) {
sb.append(Modifier.toString(cls.getModifiers())).append(" ")
.append(cls.getSimpleName()).append("\n");
sb.append("注解值: ").append(myClassAnnotation.value()).append("\n\n");
}
sb.append("Field注解:").append("\n");
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
MyFieldAnnotation fieldInfo = field.getAnnotation(MyFieldAnnotation.class);
if (fieldInfo != null) {
sb.append(Modifier.toString(field.getModifiers())).append(" ")
.append(field.getType().getSimpleName()).append(" ")
.append(field.getName()).append("\n");
sb.append("注解值: ").append(fieldInfo.name()).append("\n\n");
}
}
sb.append("Method注解:").append("\n");
Method[] methods = cls.getDeclaredMethods();
for (Method method : methods) {
MyMethodAnnotation methodInfo = method.getAnnotation(MyMethodAnnotation.class);
if (methodInfo != null) {
sb.append(Modifier.toString(method.getModifiers())).append(" ")
.append(method.getReturnType().getSimpleName()).append(" ")
.append(method.getName()).append("\n");
sb.append ( " Annotation value :") .append ( "\ n ");
sb.append("name: ").append(methodInfo.name()).append("\n");
sb.append("age: ").append(methodInfo.age()).append("\n");
}
}
System.out.print(sb.toString());
}
}
Test results are as follows:
Class Notes:
public TestRuntimeAnnotation
Notes Value : test Class
Field Notes:
public String fieldInfo
Notes Value : fieldName
Method notes:
public static String getMethodInfo
Notes values :
name: zhangsan
age: 0
Defined Note
The annotation can verify member property is empty, length, offers several common regular match, you can use regular custom to judge the legality of property, and can provide a description for this member.
Defined Note
The annotation can verify member property is empty, length, offers several common regular match, you can use regular custom to judge the legality of property, and can provide a description for this member.
package org.xdemo.validation.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.xdemo.validation.RegexType;
/**
* Data Validation
* @author Goofy
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.PARAMETER})
public @interface DV {
// Can be empty
boolean nullable() default false;
// maximum length
int maxLength() default 0;
// minimum length
int minLength() default 0;
// for several commonly used regular verification
RegexType regexType() default RegexType.NONE;
// custom regular verification
String regexExpression() default "";
// parameter or field descriptions , so that the abnormality information can be displayed friendly
String description() default "";
}
Analytical notes
package org.xdemo.validation.annotation.support;
import java.lang.reflect.Field;
import org.xdemo.validation.RegexType;
import org.xdemo.validation.annotation.DV;
import org.xdemo.validation.utils.RegexUtils;
import org.xdemo.validation.utils.StringUtils;
/**
* Notes resolved
* @author Goofy
*/
public class ValidateService {
private static DV dv;
public ValidateService() {
super();
}
// parsed entrance
public static void valid(Object object) throws Exception{
// get object type
Class<? extends Object> clazz=object.getClass();
// get the members of that type declaration
Field[] fields=clazz.getDeclaredFields();
// traverse the property
for(Field field:fields){
// for private member variables of privatization, by setAccessible to modify the access rights
field.setAccessible(true);
validate(field,object);
// reset the permissions will be private
field.setAccessible(false);
}
}
public static void validate(Field field,Object object) throws Exception{
String description;
Object value;
// annotation information acquisition targets members
dv=field.getAnnotation(DV.class);
value=field.get(object);
if(dv==null)return;
description=dv.description().equals("")?field.getName():dv.description();
/ ************* comment analytical work began ****************** /
if(!dv.nullable()){
if(value==null||StringUtils.isBlank(value.toString())){
throw new Exception (description + " not empty ");
}
}
if(value.toString().length()>dv.maxLength()&&dv.maxLength()!=0){
throw new Exception (description + " can not exceed " + dv.maxLength ());
}
if(value.toString().length()<dv.minLength()&&dv.minLength()!=0){
throw new Exception (description + " length of not less than " + dv.minLength ());
}
if(dv.regexType()!=RegexType.NONE){
switch (dv.regexType()) {
case NONE:
break;
case SPECIALCHAR:
if(RegexUtils.hasSpecialChar(value.toString())){
throw new Exception (description + " not contain the special character ");
}
break;
case CHINESE:
if(RegexUtils.isChinese2(value.toString())){
throw new Exception (description + " can not contain Chinese characters ");
}
break;
case EMAIL:
if(!RegexUtils.isEmail(value.toString())){
throw new Exception (description + " address format is incorrect ");
}
break;
case IP:
if(!RegexUtils.isIp(value.toString())){
throw new Exception (description + " address format is incorrect ");
}
break;
case NUMBER:
if(!RegexUtils.isNumber(value.toString())){
throw new Exception (description + " not a number ");
}
break;
case PHONENUMBER:
if(!RegexUtils.isPhoneNumber(value.toString())){
throw new Exception (description + " not a number ");
}
break;
default:
break;
}
}
if(!dv.regexExpression().equals("")){
if(value.toString().matches(dv.regexExpression())){
throw new Exception (description + " incorrect format ");
}
}
/ ************* comment parsing end ****************** /
}
}
Several classes used
package org.xdemo.validation;
/**
* Common data type enumeration
* @author Goofy
*
*/
public enum RegexType {
NONE,
SPECIALCHAR,
CHINESE,
EMAIL,
IP,
NUMBER,
PHONENUMBER;
}
Where regular classes and verification string tools please refer to the following links:
SuperUtil of RegexUtils
SuperUtil Noriyuki StringUtils
Instructions
package org.xdemo.validation.test;
import org.xdemo.validation.RegexType;
import org.xdemo.validation.annotation.DV;
public class User {
@DV(description="用户名",minLength=6,maxLength=32,nullable=false)
private String userName;
private String password;
@DV (description = " email address ", nullable = false, regexType = RegexType.EMAIL)
private String email;
public User(){}
public User(String userName, String password, String email) {
super();
this.userName = userName;
this.password = password;
this.email = email;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Test code
import org.xdemo.validation.annotation.support.ValidateService;
/**
* @author Goofy
*/
public class Test {
public static void main(String[] args){
User user=new User("张三", "xdemo.org", "[email protected]");
try {
ValidateService.valid(user);
} catch (Exception e) {
e.printStackTrace ();
}
user=new User("zhangsan","xdemo.org","xxx@");
try {
ValidateService.valid(user);
} catch (Exception e) {
e.printStackTrace ();
}
user=new User("zhangsan","xdemo.org","");
try {
ValidateService.valid(user);
} catch (Exception e) {
e.printStackTrace ();
}
}
}