Java: Copies the parent class field to a subclass by reflection.

Source: Internet
Author: User

There are times when you need to create subclasses that inherit from the parent class, especially in Java, where many classes are generated using MyBatis generator. Constructing subclasses from the parent class seems like a hassle, assigning a field-by-column assignment (I didn't find another good idea anyway).

Think of it in a way that reflects replication. Through research, did it. The main thing is to use the Fastjson inside. It is estimated that other class libraries have implemented this function, but I do not know that I can do it myself.

  

1 Importjava.beans.Statement;2 ImportJava.lang.reflect.Field;3 ImportJava.lang.reflect.Method;4 ImportJava.lang.reflect.Type;5 Importjava.util.List;6 7 ImportCom.alibaba.fastjson.JSON;8 ImportCom.alibaba.fastjson.util.DeserializeBeanInfo;9 ImportCom.alibaba.fastjson.util.FieldInfo;Ten Importcom.alibaba.fastjson.util.TypeUtils; One  A /** - * Created by FENGGQC on 2016/6/29. -  */ the  Public classCopyer { -  -  -      Public Static<b, SextendsB>voidCopy (B bo, S so)throwsillegalaccessexception { +  -         Try { +Class BC =Bo.getclass (); A             if(Bo = =NULL|| so = =NULL) { at                 return; -             } -  -  -Deserializebeaninfo Deserializebeaninfo =deserializebeaninfo.computesetters (So.getclass (), (Type) So.getclass ()); -List<fieldinfo> getters = typeutils.computegetters (Bo.getclass (),NULL); in  -List<fieldinfo> setters =deserializebeaninfo.getfieldlist (); to Object v; + FieldInfo Getterfield; - FieldInfo setterfidld; the  *              for(intj = 0; J < Getters.size (); J + +) { $ Panax NotoginsengGetterfield=Getters.get (j); -                  for(inti = 0; I < setters.size (); i++) { theSetterfidld=Setters.get (i); + //System.out.println (Setterfidld.getname ()); A //System.out.println (Getterfield.getname ()); the  +                     if(Setterfidld.getname (). CompareTo (Getterfield.getname ()) = = 0) { -v =Getterfield.getmethod (). Invoke (Bo); $ Setterfidld.getmethod (). Invoke (so,v); $                          Break; -                     } -  the                 } -             }Wuyi}Catch(Exception ex) { the System.out.println (ex.tostring ()); -         } Wu  -  About     } $  -  -}
View Code

1  Public classSubclassextendsBaseClass {2 3     PrivateDate birthday;4 5 6      PublicDate Getbirthday () {7         returnbirthday;8     }9 Ten      Public voidsetbirthday (Date birthday) { One          This. Birthday =birthday; A     } - } -  the  -  Public classBaseClass { -  -     PrivateInteger i; +     PrivateBoolean B; -  +     PrivateBoolean is; A     PrivateBoolean Isa; at  -     PrivateString Whatname; -  -  -      PublicBoolean Getb () { -         returnb; in     } -  to      Public voidSetb (Boolean b) { +          This. B =b; -     } the  *      PublicInteger Geti () { $         returni;Panax Notoginseng     } -  the      Public voidSetI (Integer i) { +          This. i =i; A     } the  +      PublicBoolean Getis () { -         returnis ; $     } $  -      Public voidSetis (Boolean is) { -          This. is =is ; the     } - Wuyi      PublicBoolean Getisa () { the         returnIsa; -     } Wu  -      Public voidSetisa (Boolean Isa) { About          This. ISA =Isa; $     } -  -      PublicString Getwhatname () { -         returnWhatname; A     } +  the      Public voidsetwhatname (String whatname) { -          This. Whatname =Whatname; $     } the}
View Code

Tested for performance:

1 @Test2      Public voidTest ()throwsInvocationTargetException, illegalaccessexception {3 4 5BaseClass BaseClass =NewBaseClass ();6Subclass Subclass=Newsubclass ();7 8BASECLASS.SETB (true);9Baseclass.seti (1010);TenBaseclass.setis (false); OneBaseclass.setwhatname ("Fgq"); A  -  -Integer i=0; theList<integer> ii=NewArraylist<integer>(); -Ii.add (1); -Ii.add (10); -Ii.add (100); +Ii.add (1000); -Ii.add (10000); +  AStopWatch stopwatch=NewStopWatch (); at  - Stopwatch.reset (); - Stopwatch.start (); - copyer.copy (BaseClass, subclass); - stopwatch.stop (); -System.out.println ("Cache the Reflection:" +string.valueof (Stopwatch.gettime ())); in  -  to  +  -          for(intj = 0; J < Ii.size (); J + +) { theI=0; * Stopwatch.reset (); $ Stopwatch.start ();Panax Notoginseng              while(i<Ii.get (j)) { -  the copyer.copy (BaseClass, subclass); +Subclass.setbirthday (NewDate ()); AI+=1; the             } + stopwatch.stop (); -System.out.println (String.Format ("%s%s", Ii.get (j), String.valueof (Stopwatch.gettime () )); $         } $  -  -  the  - System.out.println (json.tojsonstring (Subclass,serializerfeature.prettyformat, Serializerfeature.useiso8601dateformat));Wuyi  the  -}
View Code

The performance results are:

Cache the reflection:120
1 1
10 7
100 53
1000 139
10000 634

It feels OK. Oh

Java: Copies the parent class field to a subclass by reflection.

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.