1. 程式人生 > >利用發反射對物件進行賦值

利用發反射對物件進行賦值

public class Demo1 {


    public static Object getObejctParamater(String className,HashMap<String,String> map) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException, ParseException {
        Class<?> myclass= Class.forName(className);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Object object = myclass.newInstance();
        for(Map.Entry<String,String> entry:map.entrySet()){
            Field field = myclass.getDeclaredField(entry.getKey());
            field.setAccessible(true);

            if("Boolean".equals(field.getType().getSimpleName())){
                field.set(object,entry.getValue().equals("true"));
            }else if("BigDecimal".equals(field.getType().getSimpleName())){
                field.set(object, new BigDecimal(entry.getValue()));
            }else if("Date".equals(field.getType().getSimpleName())){
                field.set(object, simpleDateFormat.parse(entry.getValue()));
            }else if("Timestamp".equals(field.getType().getSimpleName())){
                field.set(object, Timestamp.valueOf(entry.getValue()));
            }else if(field.getType().isEnum()){
                field.set(object,Enum.valueOf((Class<Enum>) field.getType(), entry.getValue()));
            }else if("int".equals(field.getType().getSimpleName())||"Integer".equals(field.getType().getSimpleName())){
                field.set(object, Integer.parseInt(entry.getValue()));
            }else if ("String".equals(field.getType().getSimpleName())){
                field.set(object,entry.getValue());
            }
//            System.out.println(field.get(object));

        }
        return object;
    }

    public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException, ClassNotFoundException, ParseException {

    /*    try {
            Class<?> myclass= Class.forName("com.lu.entities.Group");

            Method method=myclass.getDeclaredMethod("setGroup_name", String.class);
            method.invoke(myclass.newInstance(),"testname");

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }*/


        HashMap<String, String> map = new HashMap<String, String>();
        map.put("group_name", "test_groupname");
        map.put("group_desc", "test_group_desc");
        map.put("id", "test_id");
        map.put("test_field", "mytest_field");
        map.put("flag", "false");
        map.put("price", "3000");
        map.put("brithday", "1990-12-11 15:00:00");
        map.put("updated_at", "1990-12-11 15:00:00");
        map.put("colorEnum", "BLACK");
        map.put("age", "11");
//        map.put("count", "9");


        Object group = getObejctParamater("com.my.practise.reflection.Student", map);
        System.out.println(group.toString());








    /*    Class c = Class.forName("com.my.practise.reflection.Student");
        Field[] fs = c.getDeclaredFields();

        //定義可變長的字串,用來儲存屬性
        StringBuffer sb = new StringBuffer();
        //通過追加的方法,將每個屬性拼接到此字串中
        //最外邊的public定義
        sb.append(Modifier.toString(c.getModifiers()) + " class " + c.getSimpleName() +"{\n");
        //裡邊的每一個屬性
        for(Field field:fs){
            sb.append("\t");//空格
            sb.append(Modifier.toString(field.getModifiers())+" ");//獲得屬性的修飾符,例如public,static等等
            sb.append(field.getType() + " ");//屬性的型別的名字
            sb.append(field.getName()+";\n");//屬性的名字+回車
        }

        sb.append("}");

        System.out.println(sb);*/


    }
}