Java Custom annotation Implementation process __java

Source: Internet
Author: User

Step
1, create a custom annotation class, add a checksum rule
2, parse a custom annotation class and implement a validation method
3, create a test class and declare a custom note
4, write a JUnit test class test Results custom annotation Class

Package com.swk.common.annotation;
Import Java.lang.annotation.ElementType;
Import java.lang.annotation.Retention;
Import Java.lang.annotation.RetentionPolicy;

Import Java.lang.annotation.Target; 
   /** * Custom Annotation class * @author Fuyuwei * @Retention: A retention policy that defines annotations * @Retention (retentionpolicy.source) annotations exist only in the source code and are not included in the class byte code file @Retention (retentionpolicy.class) default retention policy, annotations are present in the CLASS bytecode file but not available at run time, @Retention (retentionpolicy.runtime) annotations will be found in the CLA  SS bytecode file, which can be obtained by reflection to @Target annotation type declaration constructor constructor declaration FIELD field declaration (including enumeration constants) Local_variable local variable declaration method Method declaration PACKAGE Package declaration PARAMETER parameter declaration type class, interface (including annotation type) or enum declaration/@Retention (Retentionpolicy.runtime) @Target ({Elementt Ype.
     Type,elementtype.field,elementtype.parameter}) Public @interface customannotation {/** * is empty * @return

    * * Boolean isNull () default false;

    /** * Maximum length * @return/int maxLength () default 8; /** * Field Description * @return/String description () deFault ""; }
Implement custom annotation class rules read and verify
Package com.swk.common.annotation;
Import Java.lang.reflect.Field;

Import Java.util.concurrent.ConcurrentHashMap;

Import Org.springframework.util.StringUtils;
Import Com.swk.common.enums.CommonPostCode;


Import com.swk.common.exception.PostingException; /** * resolves the custom annotation and completes the checksum * @author Fuyuwei/public class Annotationchecker {private final static CONCURRENTHASHMAP&L T

    string,field[]> Fieldsmap = new concurrenthashmap<string, field[]> ();
    Public Annotationchecker () {super ();  public static void Checkparam (Object object) throws postingexception{class<? extends object> =
        Object.getclass ();
        field[] fields = NULL;
        if (Fieldsmap.containskey (Clazz.getname ())) {fields = Fieldsmap.get (Clazz.getname ()); }//GetFields: Gets all public fields of a class, including the parent class, and Getdeclaredfields obtains all the declared fields of a class, that is, the general, private, and proteced.
            But not including the parent class's declaration field else{fields = Clazz.getdeclaredfields (); FieLdsmap.put (Clazz.getname (), fields);
                for (field Field:fields) {synchronized (field) {field.setaccessible (true);
                Check (field, object);
            Field.setaccessible (FALSE); The private static void check (Field field,object Object) throws postingexception{String Descri
        ption;
        Object value = null;
        Customannotation CA = field.getannotation (customannotation.class);
        try {value = Field.get (object);
        catch (IllegalArgumentException e) {e.printstacktrace ();
        catch (Illegalaccessexception e) {e.printstacktrace ();
        } if (ca = = null) return;
        If there is no callout description The default display field name Description = Ca.description (). Equals ("")? Field.getname (): Ca.description (); if (!ca.isnull ()) {if (value = NULL | | Stringutils.isempty (value.tostring (). Trim ())) {throw new Postingexception (CommonPostCode.PARAM_LENGTH.getErrorCode (), description+ "" +commonpostcode.param_null.geterrormesage ()); } if (Value.tostring (). Length () > Ca.maxlength ()) {throw new Postingexception (Commonpostco De.
        Param_length.geterrorcode (), description+ "" +commonpostcode.param_length.geterrorcode ()); }
    }
}
to create a dependent other class Enumeration Class
Package com.swk.common.enums;

public enum Commonpostcode {

    param_null ( -1, "PARAM required"),
    param_length ( -2, "PARAM too Long");

    private int errorcode;

    Private String errormesage;


    Private Commonpostcode (int errorcode, String errormesage) {
        this.errorcode = errorcode;
        This.errormesage = Errormesage;
    }

    public int GetErrorCode () {return
        errorcode;
    }

    public void Seterrorcode (int errorcode) {
        this.errorcode = errorcode;
    }

    Public String Geterrormesage () {return
        errormesage;
    }

    public void Seterrormesage (String errormesage) {
        this.errormesage = errormesage;
    }


}
Custom Exception Classes
Package com.swk.common.exception;

public class Postingexception extends RuntimeException {

    private static final long Serialversionuid = 596940457958033 1293L;

    private int errorcode;

    Private String errormessage;

    Public postingexception (int errorcode, String errormessage) {
        super ();
        This.errorcode = errorcode;
        This.errormessage = errormessage;
    }

    public int GetErrorCode () {return
        errorcode;
    }

    public void Seterrorcode (int errorcode) {
        this.errorcode = errorcode;
    }

    Public String GetErrorMessage () {return
        errormessage;
    }

    public void Seterrormessage (String errormessage) {
        this.errormessage = errormessage;
    }



}
to create a test class that declares custom annotations
Package com.swk.request;

Import com.swk.common.annotation.CustomAnnotation;

public class Userinforequest {

    @CustomAnnotation (isnull=false,maxlength=4,description= "name")
    private String Name;

    @CustomAnnotation (isnull=false,maxlength=11,description= "mobile phone number")
    private String mobile;

    Public String GetName () {return
        name;
    }

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

    Public String Getmobile () {return
        mobile;
    }

    public void Setmobile (String mobile) {
        this.mobile = mobile;
    }


}

writing JUnit test classes
Package com.swk.test.annotation;

Import Org.junit.Test;
Import Org.junit.runner.RunWith;
Import org.springframework.test.context.ContextConfiguration;
Import Org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

Import Com.sun.istack.internal.logging.Logger;
Import Com.swk.common.annotation.AnnotationChecker;
Import com.swk.common.exception.PostingException;
Import Com.swk.request.UserInfoRequest;

@RunWith (Springjunit4classrunner.class)
@ContextConfiguration (locations = {"Classpath:spring-mybatis.xml"}) Public
class Annotationtest {

    private Logger Logger = Logger.getlogger (annotationtest.class);

    @Test public
    void Testannotation () {
        userinforequest request = new Userinforequest ();
        try {
            Annotationchecker.checkparam (request);
        } catch (Postingexception e) {
            logger.info ( E.geterrorcode () + ":" +e.geterrormessage ());}}}

Run results

@RunWith (Springjunit4classrunner.class)
@ContextConfiguration (locations = {"Classpath:spring-mybatis.xml"}) Public
class Annotationtest {

    private Logger Logger = Logger.getlogger (annotationtest.class);

    @Test public
    void Testannotation () {
        userinforequest request = new Userinforequest ();
        Request.setname ("Qi Tian San Sun wukong");
        try {
            Annotationchecker.checkparam (request);
        } catch (Postingexception e) {
            logger.info (e.geterrorcode () + ":" +e.geterrormessage ());}}}

Run results

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.