Java中通过反射获取泛型实例

本文转自:http://m.blog.csdn.net/jackielee_first/article/details/53365708

首先,创建一个Students的实体类

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;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public int getScore() {
        return score;
    }
    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=" + gender + ", birthday=" + birthday + ", score="
                + score + ", cid=" + cid + "]";
    }

}

核心代码

package com.jackie.day11;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.Map;

/**
 * 通过反射获取泛型实例
 * @author Administrator
 *
 */
public abstract class Genericity<T> {
    /**
     * 当前操作的实体的类型信息
     */
    @SuppressWarnings("rawtypes")
    protected Class clazz;

    @SuppressWarnings("unchecked")
    public Genericity() {
        // 通过反射机制获取子类传递过来的实体类的类型信息
        ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        clazz = (Class<T>) type.getActualTypeArguments()[0];
    }

    /**
     * 获取指定实例的所有属性名及对应值的Map实例
     * 
     * @param entity
     *            实例
     * @return 字段名及对应值的Map实例
     */
    protected Map<String, Object> getFieldValueMap(T entity) {
        // key是属性名,value是对应值
        Map<String, Object> fieldValueMap = new HashMap<String, Object>();

        // 获取当前加载的实体类中所有属性(字段)
        Field[] fields = this.clazz.getDeclaredFields();

        for (int i = 0; i < fields.length; i++) {
            Field f = fields[i];
            String key = f.getName();// 属性名 
            Object value = null;//属性值  
            if (! "serialVersionUID".equals(key)) {// 忽略序列化版本ID号
                f.setAccessible(true);// 取消Java语言访问检查
                try {
                    value =f.get(entity);
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                fieldValueMap.put(key, value);
            }
        }
        return fieldValueMap;
    }
}

测试类:

package com.jackie.day11;

import java.util.Date;
import java.util.Map;
import java.util.Set;

/**
 * 测试:通过反射获取泛型实例
 * @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(33);
        ss.setGender("男");
        ss.setName("张三");
        ss.setScore(99);
        ss.setSid(4);

        Map<String,Object> map = gt.getFieldValueMap(ss);
        //遍历这个map对象
        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);
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值