Java 反射赋值

package lotusdata;


/**
 * Created by Amadeus on 2018/11/14.
 */

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ImportFile {
    /**
     * 取对象所有成员名列表
     * @param f
     * @return 对象成员名列表
     */
    public static List<String> getComponentsNameList(Object f) {
        // 获取f对象对应类中的所有属性域
        Field[] fields = f.getClass().getDeclaredFields();
        List<String> nameList = new ArrayList<String>();
        for(int i = 0 , len = fields.length; i < len; i++) {
            // 对于每个属性,获取属性名
            nameList.add(fields[i].getName());
        }
        return nameList;
    }

    /**
     * 为对象o中与map的key值相同的成员赋予value值
     * @param o
     * @param map
     */
    public static void setAllComponentsName(Object o, Map<String, Object> map){
        List<String> keyList = getComponentsNameList(o);
        for(String key:keyList){
            try {
                Field field = o.getClass().getDeclaredField(key);
                boolean accessFlag = field.isAccessible();
                field.setAccessible(true);
                field.set(o, (String)map.get(key));
                field.setAccessible(accessFlag);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 控制台输出entity的所有成员名和值
     * @param entity
     */
    public static void getAllComponentsName(Object entity){
        // 获取f对象对应类中的所有属性域
        Field[] fields = entity.getClass().getDeclaredFields();
        for(int i = 0 , len = fields.length; i < len; i++) {
            // 对于每个属性,获取属性名
            String varName = fields[i].getName();
            try {
                // 获取原来的访问控制权限
                boolean accessFlag = fields[i].isAccessible();
                // 修改访问控制权限
                fields[i].setAccessible(true);
                // 获取在对象f中属性fields[i]对应的对象中的变量
                Object o = fields[i].get(entity);
                System.out.println("传入的对象中包含一个如下的变量:" + varName + " = " + o);
                // 恢复访问控制权限
                fields[i].setAccessible(accessFlag);
            } catch (IllegalArgumentException ex) {
                ex.printStackTrace();
            } catch (IllegalAccessException ex) {
                ex.printStackTrace();
            }
        }
    }

    public static boolean isAllMapValueNull(Map<String, Object> map){
        for (Object value : map.values()) {
            if(value != null)
                return false;
        }
        return true;
    }

    /**
     * 将map中的value值根据key赋予entity,并调用insert
     * @param entity
     * @param map
     */
    public static void insert(Object entity, Map<String, Object> map){
        System.out.println("实体开始-----");
        ImportFile.setAllComponentsName(entity, map);
        ImportFile.getAllComponentsName(entity);
        InsertData insertData = (InsertData)entity;
        insertData.insertData();
        System.out.println("实体结束-----");
    }

    public static void importFile(String filePath, String className){
        Map<String, Object> map = new HashMap<String, Object>();
        List<String> keyList = null;
        try {
            keyList = getComponentsNameList(Class.forName(className).newInstance());
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            FileReader fr = new FileReader(filePath);
            BufferedReader bf = new BufferedReader(fr);

            label:
            while (true) {
                //根据类的全路径实例化相应的类
                Class c = Class.forName(className);
                Object entity = c.newInstance();
                for(String key:keyList){
                    map.put(key, null);
                }
                while(true){
                    String line = bf.readLine();// 按行读取字符串
                    if(line == null){
                        if(!isAllMapValueNull(map))
                            insert(entity, map);
                        break label;
                    }
                    if(line.equals("")){
                        if(!isAllMapValueNull(map))
                            insert(entity, map);
                        break;
                    }
                    line = line.trim();//若字符串有值则去掉前后空格
                    /*这个if是读取文件最后的文章*/
                    if(line.equals("text")){
                        String text = "";
                        line = bf.readLine();
                        while(!line.trim().equals("/text")){
                            text += line+"\n";
                            line = bf.readLine();
                        }
                        map.put("text",text);
                    }else
                    if(line.indexOf(":") > -1){
                        int index = line.indexOf(":");
                        String key = line.substring(0,index).replace("$","");
                        String value = line.substring(index+1,line.length()).trim();
                        if(map.containsKey(key)){
                            map.put(key,value);
                        }
                    }
                }
                map.clear();

            }
            bf.close();
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }


    }


    public static void main(String[] args) {
        String filePath = "C:\\Users\\Amadeus\\Desktop\\test.txt";
        String className= "com.fjc.learn.reflection.Entity";
        ImportFile.importFile(filePath, className);
//        try {
//            Class c = Class.forName(className);
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        }
//        ImportFile.setAllComponentsName(new Entity());
//        Entity entity = new Entity();
//        setAllComponentsName(entity);
//        System.out.println(entity.a);
//        System.out.println(entity.b);
//        System.out.println(entity.c);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值