Java reflection implements the same property value replication for different objects

Source: Internet
Author: User

1. This method will filter the final field

2. This method filters the object fields

3. This method is compatible with the replication of attribute values between objects and between different objects

Package Com.bin.design.util;import Java.lang.reflect.field;import java.lang.reflect.method;import Java.lang.reflect.modifier;import Java.util.arrays;import Java.util.list;import com.bin.design.domain.People; Import Com.bin.design.domain.User; Public classTools {/** * Object Same Property copy * * @param obj * @param toresult * @return * @throws Exception * Conversion Error*/     Public Static<T> T cloneobj (Object obj, class<t>Toresult) {        if(obj = =NULL) {            return NULL; }        Try{T T=toresult.newinstance (); Field[] Fields=Toresult.getdeclaredfields ();  for(Field field:fields) {field.setaccessible (true);//Modify access Permissions                if(Modifier.isfinal (Field.getmodifiers ()))Continue; if(Iswraptype (field)) {String Firstletter= Field.getname (). SUBSTRING (0,1). toUpperCase ();//Capitalize first letterString Getmethodname ="Get"+ Firstletter + field.getname (). SUBSTRING (1); String Setmethodname="Set"+ Firstletter + field.getname (). SUBSTRING (1); Method GetMethod= Obj.getclass (). GetMethod (Getmethodname);//getting a Get method from a source objectMethod Setmethod = Toresult.getmethod (Setmethodname,NewClass[] {field.gettype ()});//Get Set method from target object//if both the get and set methods are fetched from an object, an object that appears as an instance of declaring class error//like:user{name} people{name}//because if obtained from the source object, when the Setmethod.invoke call, although the name is the same, due to the different classes, cause//the method being called is not the proper method in the target object.                    The actual is: GetMethod = Com.package.User.getName (); setmethod = Com.package.User.setName (); //The result of the Setmethod.invoke call becomes people.setname () = = people. (Com.package.User.setName ())//SetName Here is not people should have, so error//Similarly, if fetched from the target object, there will be an error when the Getmethod.invoke is called. //Therefore, the acquisition of GetMethod and Setmethod should be treated differently depending on the source object and the target object. //of course, if you just make a separate copy of the object, you don't have to worry about calling a method that doesn't belong to itself, and you don't have to differentiate between object get and setObject Value= Getmethod.invoke (obj);//Get Gets the value of the source objectSetmethod.invoke (T,NewObject[] {value});//set is the value of the target object                }            }            returnT; } Catch(Exception e) {System. out. println (E.getmessage ());        E.printstacktrace (); }        return NULL; }    /** * is the base type, package type, String type*/    Private Staticboolean iswraptype (Field field) {string[] types= {"Java.lang.Integer","java.lang.Double","java.lang.Float","Java.lang.Long",                "Java.lang.Short","Java.lang.Byte","Java.lang.Boolean","Java.lang.Char","java.lang.String","int",                "Double","Long"," Short","byte","Boolean","Char","float" }; List<String> typelist =arrays.aslist (types); returnTypelist.contains (Field.gettype (). GetName ())?true:false; }         Public Static voidMain (string[] args) {User User=NewUser (); User.setname ("AAA"); User.setpassword ("VVV"); System. out. println ("1"+user.getname () +User.getpassword ()); People people=Newpeople (); System. out. println ("2"+people.getname ()); User Users= Cloneobj (User,user.class); System. out. println ("3"+users.getname ()); People p= Cloneobj (user,people.class); System. out. println ("4"+p.getname ()); }}

Java reflection implements the same property value replication for different objects

Related Article

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.