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;
        }
    }
  • 相关阅读:
    leetcode : 3 sum
    leetcode : Merge two sorted lists
    算法:海量数据问题
    计算机基础:数据库
    计算机基础:Linux
    Java:JVM
    Java:Basic/集合框架/多线程
    Java:面试题
    框架:SSM整合
    LeetCode: Tags-[Bit Manipulation]
  • 原文地址:https://www.cnblogs.com/therunningfish/p/7268797.html
Copyright © 2011-2022 走看看