zoukankan      html  css  js  c++  java
  • 反射实例

    package test;
    
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Map;
    
    public class TestReflex {
    
        public static Map<String,String> convertResponseStr(Object obj){
            try{
                Map<String,String> mapRes = new HashMap<String,String>();
                Class<? extends Object> ownerClass = obj.getClass();
                Field [] fields = ownerClass.getDeclaredFields();
                for(Field f : fields){
                    String methodName = f.getName().substring(0, 1).toUpperCase()+ f.getName().substring(1);
                    Method  method = ownerClass.getMethod("get" + methodName);
                    Object getValue = method.invoke(obj);
                    String typeName = method.getGenericReturnType().toString();
                    if(getValue == null){
                        if(typeName.contains("java.util.List"))getValue = new ArrayList<>();
                        else if(typeName.contains("java.util.Map"))getValue = new HashMap<>();
                        else if(typeName.contains("java.lang.String"))getValue = "";
                        else if(typeName.contains("java.lang.Integer"))getValue = 0;
                        else if(typeName.contains("java.lang.Double"))getValue = 0;
                        else if(typeName.contains("java.util.Date"))getValue ="";
                        else getValue = "";
                    }
                    mapRes.put(f.getName(), String.valueOf(getValue));
                }
                return mapRes;
            }catch(Exception e){
                e.printStackTrace();
                return new HashMap<String,String>();
            }
        }
        
        public static void main(String[] args){
            TestObject to = new TestObject();
            to.setName("to001");
            to.setAge(28);
            System.out.println(convertResponseStr(to));
        }
    }
    
    class TestObject{
        private String name;
        private Integer age;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
    }
  • 相关阅读:
    Codeforces 492E Vanya and Field
    Codeforces 492D Vanya and Computer Game
    HDU 5125 magic balls(线段树+DP)
    HDU 5124 lines
    Codeforces 488D Strip (set+DP)
    FZU 2079 最大获利(线段树+DP)
    Codeforces 490D Chocolate
    Codeforces 490C Hacking Cypher
    HDU
    HDU
  • 原文地址:https://www.cnblogs.com/therunningfish/p/7268797.html
Copyright © 2011-2022 走看看