Convert a map to a bean using annotations and reflections

Source: Internet
Author: User

First, Java annotations

Java annotation-related classes are placed under the java.lang.annotation package, the main content contains 4 meta-annotations and two meta-annotations of the enumeration class values, relatively simple, from the JDK question and answer to understand

4 meta-Annotations:

documented: Indicates that a comment of a type will be documented by Javadoc and similar default tools. You should use this type to annotate declarations of these types: their annotations affect the use of elements commented by their clients. If a type declaration is annotated with documented, its comment becomes part of the public API for the annotation element.


inherited: Indicates that the annotation type is automatically inherited. If a inherited meta comment exists in the annotation type declaration, and the user queries the annotation type in a class of declaration, and there is no comment of that type in that declaration, the annotation type is automatically queried in the superclass of the class. This process repeats until a comment of this type is found or the top level (Object) of the class hierarchy is reached. If no superclass has a comment of that type, the query indicates that the current class does not have such a comment.


Note that if you use anything other than the comment type comment class, the meta-comment type is not valid. Also note that this meta-comment only facilitates the inheritance of comments from the superclass, and the annotations to the implemented interfaces are not valid.


Retention: Indicates how long comments for the annotation type are to be retained. If the Retention comment does not exist in the annotation type declaration, the retention policy defaults to Retentionpolicy.class.

The Target meta Comment is valid only if the meta-comment type is used directly for comments. Invalid if the meta-comment type is used as a member of another annotation type.

Retentionpolicy.source---------------------------------annotations will be discarded by the compiler

Retentionpolicy.class-----------------------------------annotations are available in the CLASS file, but are discarded by the VM

The Retentionpolicy.runtime VM-------will also retain annotations at run time, so you can read the information of the annotations through the reflection mechanism.


Target: indicates the kind of program element that the annotation type applies to. If a Target meta comment does not exist in the annotation type declaration, the declared type can be used on either program element. If such a meta-comment exists, the compiler enforces the specified usage limit

Elemenettype.constructor----------------------------Constructor Declaration

Elemenettype.field--------------------------------------domain declarations (including enum instances)

Elemenettype.local_variable-------------------------local variable declarations

Elemenettype.method----------------------------------Method declaration

Elemenettype.package---------------------------------Package Declaration

Elemenettype.parameter------------------------------Parameter Declaration

Elemenettype.type---------------------------------------classes, interfaces (including annotation types) or enum declarations


ii. Examples of annotations  

This example has 3 files: annotation class annotation_1, using annotation class useannotation, parsing annotation class parseannotation

package com.annotation;import java.lang.annotation.elementtype ;import java.lang.annotation.retention;import java.lang.annotation.retentionpolicy;import  Java.lang.annotation.Target; @Target ({elementtype.type, elementtype.method, elementtype.constructor,  elementtype.field}) @Retention (retentionpolicy.runtime) public  @interface  annotation_1 { String name (); Int id ()  default 0; Class gid ();} 
package com.annotation;import java.lang.reflect.method;@ Annotation_1 (name= "Useannotation",  id=1, gid=long.class) public class useannotation {@ Annotation_1 (name= "a",  gid=integer.class) public int a; @Annotation_1 (name= "Constractor_method",  gid=method.class) Public useannotation () {} @Annotation_1 (name= "Geta",  id=2, gid= Method.class) Public int geta () {RETURN THIS.A;} @Annotation_1 (name= "SetA",  id=2, gid=method.class) Public void seta (int a) {THIS.A  = a;}} 
package com.annotation;import java.lang.annotation.annotation;import  java.lang.reflect.accessibleobject;import java.lang.reflect.field;import java.lang.reflect.method; public class parseannotation {/** *  parsing class annotations  *  @throws   Classnotfoundexception  */public void parseclass ()  throws classnotfoundexception {//class clazz = class.forname ("com.annotation.UseAnnotation"); Annotation[] as = useannotation.class.getannotations (); for (Annotation a: as) { annotation_1 a1 =  (annotation_1) A; System.out.println ("Class: name="  + a1.name ()  +  ",  id="  + a1.id ()  +  ",  gid="  + a1.gid ());}} Annotation of/** *  parsing method  */public void parsemethod () {method[] methods =  UseAnnotation.class.getMethods (); This.parse (methods);} /** *  annotation for parsing member variables   */public void parsEfield () {field[] fields = useannotation.class.getfields (); This.parse (fields);} Private <t extends accessibleobject> void parse (T[] ts) {for (T t:  ts) {annotation annotation = t.getannotation (Annotation_1.class); if (annotation ==  null) {System.out.println (T.getclass (). GetName ()  +  " do not have annotation _1 ");} else{annotation_1 a1 =  (annotation_1) Annotation; System.out.println (T.getclass (). GetName ()  +  ":  name="  + a1.name ()  +  ",  id= " + a1.id ()  + ",  gid= " + a1.gid ());}}} Public static void main (String[] args)  throws classnotfoundexception { Parseannotation pa = new parseannotation ();p a.parseclass ();p a.parsemethod ();p A.parsefield ( );}}


Iii. using annotations and reflections to transform a map into a bean

This example uses annotations and reflection techniques to convert a map type into a corresponding bean

It consists of 4 main classes: annotation class pojoannotation, bean class User, Conversion tool class Pojomappingutil, test class Pojotest

Package Com.annotation.userdemo;import Java.lang.annotation.retention;import Java.lang.annotation.RetentionPolicy ; @Retention (retentionpolicy.runtime) public @interface pojoannotation {String name ();}
package com.annotation.userdemo;public class user {@ Pojoannotation (name= "name") private string name; @PojoAnnotation (name= "age") private integer  Age;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;} @Overridepublic  string tostring ()  {return  "User [name="  + name +  ",  age="  + age +  "]";}} 
package com.annotation.userdemo;import java.lang.reflect.field;import  java.lang.reflect.invocationtargetexception;import java.lang.reflect.method;import java.util.map; public class pojomappingutil {/** *  Place the key in the map with the annotation consistent value into the corresponding member variable  */public  Static <t> t parsepoje (map<string, object> map, class<t>  Clazz)  throws InstantiationException, IllegalAccessException, NoSuchMethodException,  securityexception, illegalargumentexception, invocationtargetexception{t t =  Clazz.newinstance (); Field[] fields = clazz.getdeclaredfields (); for (Field field : fields) { Pojoannotation pojoannotation = field.getannotation (Pojoannotation.class); if (PojoAnnotation  != null) {Object o = map.get (Pojoannotation.name ()), if (o != null) {String  fieldname = field.getname (); MethoD method = clazz.getmethod ("Set"  + fieldname.substring (0, 1). ToUpperCase ()   + fieldname.substring (1),  o.getclass ()); Method.invoke (T, o);}} Return t;}}
Package Com.annotation.userdemo;import Java.lang.reflect.invocationtargetexception;import Java.util.HashMap; Import Java.util.map;public class Pojotest {public static void main (string[] args) throws instantiationexception, illegal Accessexception, Nosuchmethodexception, SecurityException, IllegalArgumentException, InvocationTargetException {Map <string, object> map = new hashmap<string, object> (); Map.put ("NAME", "xiaoming"); Map.put ("Age", 10); User user = Pojomappingutil.parsepoje (map, User.class); SYSTEM.OUT.PRINTLN (user);}}


This article is from "Tu wei" blog, please be sure to keep this source http://1531439090.blog.51cto.com/6088789/1835058

Convert a map to a bean using annotations and reflections

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.