Java implementation has the same attribute name and similar types of Pojo, Dto, VO and other mutual transfer

Source: Internet
Author: User
Tags getmessage object object

Applied to actual project: 1.thrift object to the DTO

The interaction between 2.pojo and DTO

The reciprocal transfer between 3.pojo and VO


Or do you prefer to stick code directly csdn code address

1. Core conversion Tool class, no processing for particularly complex types because the business scenario is not yet covered

Package Littlehow.convert;
Import Org.slf4j.Logger;

Import Org.slf4j.LoggerFactory;
Import Java.lang.reflect.Field;
Import Java.lang.reflect.Method;
Import Java.lang.reflect.ParameterizedType;
Import Java.lang.reflect.Type;
Import Java.math.BigDecimal;
Import Java.sql.Timestamp;
Import java.util.*;

Import Java.util.concurrent.ConcurrentHashMap; /** * Pojoconvertutil * *@authorLittlehow *@time2017-05-03 16:54 */public class Pojoconvertutil {private static Logger Logger = Loggerfactory.getlogger (pojoconvert
    Util.class); /** * variable cache/private static final map<string, map<string, field>> cachefields = new Concurrenth
    Ashmap<> ();
    private static final set<class> Basicclass = new hashset<> ();
        static {Basicclass.add (Integer.class);
        Basicclass.add (Character.class);
        Basicclass.add (Byte.class);
        Basicclass.add (Float.class);
        Basicclass.add (Double.class);
        Basicclass.add (Boolean.class);
        Basicclass.add (Long.class);
        Basicclass.add (Short.class);
        Basicclass.add (String.class);
    Basicclass.add (Bigdecimal.class); /** * Converts a type with the same attribute *@paramOrig *@param<T> *@return */public static <T> T Convertpojo (Object orig, class<t> targetclass) {try {t target
            = Targetclass.newinstance ();
            /** gets all the variables of the source object/field[] fields = Orig.getclass (). Getdeclaredfields ();
                for (field Field:fields) {if (IsStatic (field)) continue;
                /** Get Target method * * Field Targetfield = Gettargetfield (Targetclass, Field.getname ());
                if (Targetfield = = null) continue;
                Object value = getfiledvalue (field, orig);
                if (value = = null) continue;
                Class type1 = Field.gettype ();
                Class type2 = Targetfield.gettype ();
                Two types are the same Boolean sametype = Type1.equals (type2);
                if (Isbasictype (type1)) {if (Sametype) SetFieldValue (Targetfield, target, value); else if (value instanceof Map && Map.class.isAssignableFrom (type2)) {//To map Setmap ((map) value, field, Targetfield, target); else if (value instanceof set && Set.class.isAssignableFrom (type2)) {//Pair set Setcollection (C
                ollection) value, field, Targetfield, target); else if (value instanceof list && List.class.isAssignableFrom (type2)) {//to List Setcollection
                ((Collection) value, field, Targetfield, target); else if (value instanceof enum && Enum.class.isAssignableFrom (type2)) {//pair of enum Setenum (enum
                ) value, field, Targetfield, target); else if (value instanceof java.util.Date && java.util.Date.class.isAssignableFrom (type2)
                {//pairs of date types, does not process extended times such as Joda packages, does not deal with calendar setdate ((Date) value, Targetfield, type2, Target, Sametype);
        } return target; The catch (Throwable t) {Logger.error ("Conversion failed:"+ t.getmessage ());
        throw new RuntimeException (T.getmessage ());  }/** * Get field value *@paramfield *@paramobj *@return * * private static Object getfiledvalue (Field field, Object obj) throws illegalaccessexception {//Get original access rights
        Boolean access = Field.isaccessible ();
            try {//Set the accessible permission field.setaccessible (true);
        return Field.get (obj);
        Finally {//restore access rights field.setaccessible (access); }}/** * Set method value *@paramfield *@paramobj *@paramValue *@throwsIllegalaccessexception * * private static void setfieldvalue (Field field, Object obj, object value) throws illegal
        accessexception {//Get the original access rights Boolean access = Field.isaccessible ();
            try {//Set the accessible permission field.setaccessible (true);
        Field.set (obj, value);
        Finally {//restore access rights field.setaccessible (access); }/** * Convert list *@paramOrig *@paramTargetclass *@param<T> *@return * * public static <T> list<t> Convertpojos (List orig, class<t> targetclass) {list<t> L
        ist = new Arraylist<> (Orig.size ());
        For (object Object:orig) {List.add (Convertpojo (object, Targetclass));
    } return list; }/** * Set map *@paramValue *@paramOrigfield *@paramTargetfield *@paramTargetObject *@param<T> * private static <T> void Setmap (Map value, field Origfield, Field Targetfield, T targetobject)
        Throws Illegalaccessexception, instantiationexception{Type origtype = Origfield.getgenerictype ();
        Type targettype = Targetfield.getgenerictype (); if (origtype instanceof parameterizedtype && targettype instanceof Parameterizedtype) {//generic type Paramete
            Rizedtype Origparameterizedtype = (parameterizedtype) origtype;
            type[] Origtypes = origparameterizedtype.getactualtypearguments ();
            Parameterizedtype Targetparameterizedtype = (parameterizedtype) targettype;
            type[] Targettypes = targetparameterizedtype.getactualtypearguments (); if (origtypes!= null && origtypes.length = 2 && targettypes!= null && targettypes.length = 2)
                {//normal generics to see if the second generic is not a base type Class Clazz = (Class) origtypes[1]; if (!isbasictype (clazz) &&!clazz.equals(Targettypes[1])
                    {//If it is not of the base type and the generics are inconsistent, you need to continue converting set<map.entry> entries = Value.entryset ();
                    Map Targetmap = Value.getclass (). newinstance (); for (Map.entry entry:entries) {targetmap.put (Entry.getkey (), Convertpojo (Entry.getvalue (), Cla
                    SS) Targettypes[1]);
                    } setfieldvalue (Targetfield, TargetObject, Targetmap);
                Return
    }} setfieldvalue (Targetfield, targetobject, value);  }/** * Settings collection *@paramValue *@paramOrigfield *@paramTargetfield *@paramTargetObject *@param<T> *@throwsIllegalaccessexception *@throwsInstantiationexception * private static <T> void Setcollection (Collection value, field Origfield, field Ta Rgetfield, T targetobject) throws Illegalaccessexception, instantiationexception{Type origtype = Origfield.getgen
        Erictype ();
        Type targettype = Targetfield.getgenerictype (); if (origtype instanceof parameterizedtype && targettype instanceof Parameterizedtype) {//generic type Paramete
            Rizedtype Origparameterizedtype = (parameterizedtype) origtype;
            type[] Origtypes = origparameterizedtype.getactualtypearguments ();
            Parameterizedtype Targetparameterizedtype = (parameterizedtype) targettype;
            type[] Targettypes = targetparameterizedtype.getactualtypearguments (); if (origtypes!= null && origtypes.length = 1 && targettypes!= null && targettypes.length = 1)
                {//normal generics to see if the second generic is not a base type Class Clazz = (Class) origtypes[0]; if (!isbasictype (Clazz) &&!clazz.equals (Targettypes[0]) {//If it is not of the base type and the generics are inconsistent, you need to continue converting Collection Collection = value.
                    GetClass (). newinstance ();
                    for (Object obj:value) {collection.add (Convertpojo (obj, (Class) targettypes[0));
                    } setfieldvalue (Targetfield, TargetObject, collection);
                Return
    }} setfieldvalue (Targetfield, targetobject, value);

     }

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.