Java annotation + reflection Application Record, javaannotation

Source: Internet
Author: User

Java annotation + reflection Application Record, javaannotation

A small example of annotation and reflection in java is recorded for reference,

The configuration page allows you to dynamically select a class that implements the Check interface, save the input parameters, and pass in the saved parameters during the real check.

The configuration page is as follows: the first line selects check 1 and three parameters need to be entered. The second line shows the drop-down menu, which is generated based on the class marked by annotation.

 

The drop-down menu is generated based on the class marked by annotation. Currently, there are three test classes. You can enter the required parameters and save them. The parameters are also defined in the class, at present, let's talk about the implementation of this part of configuration.

Customize An annotation

1 @Retention(RetentionPolicy.RUNTIME)2 @Target(ElementType.TYPE)3 public @interface AnnotBpbAssertionClass {4 5     public String descr() default "";6 }

One of the core class implements the interface to implement the assertData method, and the real method called by the core is checked,

@ AnnotBpbAssertionArg mark the input parameters. You can see the matching information on the above page.
1 @ AnnotBpbAssertionClass (descr = "Checking 1") 2 public class TestAssert1 implements AssertionClassHandler {3 4 @ AnnotBpbAssertionArg 5 private String arg1; 6 @ login 7 private String arg2; 8 @ AnnotBpbAssertionArg 9 private String arg3; 10 public String getArg1 () {11 return arg1; 12} 13 public void setArg1 (String arg1) {14 this. arg1 = arg1; 15} 16 public String getArg2 () {17 return arg2; 18} 19 public void setArg2 (String arg2) {20 this. arg2 = arg2; 21} 22 public String getArg3 () {23 return arg3; 24} 25 public void setArg3 (String arg3) {26 this. arg3 = arg3; 27} 28 @ Override29 public AssertionResult assertData () {30 31} 32 33 34}

 

To ensure high efficiency, the class labeled with annotation is written into the memory when spring loads bean. The service needs to implement InitializingBean and class scanning is used in the initialization method.

First, obtain Reflections. PKG_NAME indicates the path of the scan package. If you think it is useless, you can capture it once during the call.

 

 1  private static Reflections getRef(String pkgName) { 2         String sPkgName = pkgName == null ? PKG_NAME : pkgName; 3  4         Set<URL> clzLoaderUrls = ClasspathHelper.forPackage(sPkgName); 5         Set<URL> webInfoLibUrls = Collections.emptySet(); 6         Set<URL> scanUrls = new LinkedHashSet<URL>(); 7  8         try { 9             ServletContext servletContext = WebContextInfo.getInstance().getParentServletContext();10             webInfoLibUrls = ClasspathHelper.forWebInfLib(servletContext);11             URL webInfoClassUrls = ClasspathHelper.forWebInfClasses(servletContext);12             if(webInfoClassUrls != null){13                 scanUrls.add(webInfoClassUrls);14             }  15         } catch (Exception e) {16             LG.warn(ClassScanner.class.getSimpleName(),17                     "get webinf lib/class failed., err: {0}", e.getMessage());18         }19 20         scanUrls.addAll(webInfoLibUrls);21         scanUrls.addAll(clzLoaderUrls);22 23         ConfigurationBuilder cfgBuilder = new ConfigurationBuilder();24         cfgBuilder.filterInputsBy(new FilterBuilder.Include(FilterBuilder.prefix(sPkgName)));25         cfgBuilder.addScanners(26                 new SubTypesScanner(), 27                 new TypeAnnotationsScanner(), 28                 new MethodAnnotationsScanner(), 29                 new FieldAnnotationsScanner());30         cfgBuilder.setUrls(scanUrls);31 32         Reflections refs = new Reflections(cfgBuilder);33         return refs;34     }

Obtain all the class sets marked with annotation.

        Reflections ref = getRef();        Set<Class<?>> ret = ref.getTypesAnnotatedWith(annotation);   

Encapsulate the information of class and annotation in the class BpbAssertionClassMeta. You can see some methods of class and annotation.

 

If (CollectionUtils. isNotEmpty (clazzSet) {for (Class <?> Clazz: clazzSet) {BpbAssertionClassMeta meta = new BpbAssertionClassMeta (); List <ArgMeta> argMetas = new ArrayList <BpbAssertionClassMeta. argMeta> (); meta. setArgs (argMetas); meta. setClassName (clazz. getCanonicalName (); AnnotBpbAssertionClass annotation = clazz. getAnnotation (AnnotBpbAssertionClass. class); // obtain annotation meta. setDesc (annotation. descr (); metas. add (meta); Field [] declaredFields = fig Zz. getDeclaredFields (); // obtain all fields of the class if (declaredFields! = Null) {for (Field field: declaredFields) {if (field. isAnnotationPresent (AnnotBpbAssertionArg. class) {// whether the annotation if (String. class. isAssignableFrom (field. getType () = false) {// whether the string type throw new IllegalArgumentException (String. format ("unsupported type !, Expected % s but % s found. @ field: % s, @ class: % s ", String. class. getSimpleName (), field. getType (). getSimpleName (), field. getName (), clazz. getName ();} ArgMeta argMeta = meta. new ArgMeta (); argMeta. setField (field); argMeta. setDesc (field. getName (); argMetas. add (argMeta );}}}}}

Page loop BpbAssertionClassMeta to render this page.

 

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.