Get generic instance __java by reflection in Java

Source: Internet
Author: User
Tags reflection

First, create a students entity class

Package com.jackie.day11;
Import java.io.Serializable;

Import Java.util.Date;

    public class Students implements serializable{private static final long serialversionuid = -8655172670979705548l;
    private int sid;
    private String name;
    Private String gender;
    Private Date birthday;
    private int score;

    private int CID;
    public int GetSID () {return SID;
    public void Setsid (int sid) {this.sid = SID;
    Public String GetName () {return name;
    public void SetName (String name) {this.name = name;
    Public String Getgender () {return gender;
    } public void Setgender (String gender) {This.gender = gender;
    Public Date Getbirthday () {return birthday;
    The public void Setbirthday (Date birthday) {this.birthday = birthday;
    public int Getscore () {return score;
The public void SetScore (int score) {This.score = score;    public int getcid () {return CID;
    public void Setcid (int cid) {this.cid = CID; @Override public String toString () {return "Student [sid= + Sid +", name= "+ name +", gender= "+ gen
    Der + ", birthday=" + Birthday + ", score=" + score + ", cid=" + CID + "];
 }

}

Core code

Package com.jackie.day11;
Import Java.lang.reflect.Field;
Import Java.lang.reflect.ParameterizedType;
Import Java.util.HashMap;

Import Java.util.Map;
     /** * Get generic instance through reflection * @author Administrator * */Public abstract class Genericity<t> {/** * type information for the entity currently operating

    * * @SuppressWarnings ("rawtypes") protected Class clazz;  @SuppressWarnings ("unchecked") public genericity () {//through the reflection mechanism gets the type information of the entity class passed over by a subclass Parameterizedtype type
        = (Parameterizedtype) this.getclass (). Getgenericsuperclass ();
    Clazz = (class<t>) type.getactualtypearguments () [0];
     /** * Gets a map instance of all property names and corresponding values of the specified instance * * @param entity * instance * @return Field name and map instance of corresponding value */protected Map<string, object> Getfieldvaluemap (T entity) {//key is the property name, value is the corresponding values Map<str

        ing, object> fieldvaluemap = new hashmap<string, object> (); Gets all the properties (fields) field[] fields = This.clazz.getDeclaredFiel in the currently loaded entity classDS ();
            for (int i = 0; i < fields.length i++) {Field f = fields[i]; String key = F.getname ();//property name Object value = null;//property value if (! 
                    ' Serialversionuid '. Equals (key) {//Ignore serialized version ID number f.setaccessible (true);/Cancel Java language access check try {
                Value =f.get (entity);
                catch (IllegalArgumentException e) {e.printstacktrace ();
                catch (Illegalaccessexception e) {e.printstacktrace ();
            } fieldvaluemap.put (key, value);
    } return Fieldvaluemap;
 }
}

Test class:

Package com.jackie.day11;

Import java.util.Date;
Import Java.util.Map;
Import Java.util.Set;

/**
 * Test: Get generic instance through reflection
 * @author Administrator * * */Public

class Genericitytest extends Genericity <Students> {public

    static void Main (string[] args) {

        genericitytest GT = new Genericitytest ();

        Students ss = new Students ();
        Ss.setbirthday (New Date ());
        Ss.setcid ();
        Ss.setgender ("male");
        Ss.setname ("John");
        Ss.setscore ();
        Ss.setsid (4);

        map<string,object> map = gt.getfieldvaluemap (ss);
        Traverse this Map object
        set<map.entry<string, object>> entryset = Map.entryset ();
        For (map.entry<string, object> entry:entryset) {
            String key = Entry.getkey ();
            Object value = Entry.getvalue ();
            SYSTEM.OUT.PRINTLN (key + ">>>>>>>" + value);}}

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.