Home >Java >javaTutorial >How to understand how to obtain object attribute types, attribute names, and attribute values ​​in Java

How to understand how to obtain object attribute types, attribute names, and attribute values ​​in Java

坏嘻嘻
坏嘻嘻Original
2018-09-15 15:05:472923browse

The content of this article is about how to understand java to obtain object attribute types, attribute names, and attribute values. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

/** 
 * 根据属性名获取属性值 
 * */  
   private Object getFieldValueByName(String fieldName, Object o) {  
       try {    
           String firstLetter = fieldName.substring(0, 1).toUpperCase();    
           String getter = "get" + firstLetter + fieldName.substring(1);    
           Method method = o.getClass().getMethod(getter, new Class[] {});    
           Object value = method.invoke(o, new Object[] {});    
           return value;    
       } catch (Exception e) {    
           log.error(e.getMessage(),e);    
           return null;    
       }    
   }   
     
   /** 
    * 获取属性名数组 
    * */  
   private String[] getFiledName(Object o){  
    Field[] fields=o.getClass().getDeclaredFields();  
        String[] fieldNames=new String[fields.length];  
    for(int i=0;i<fields.length;i++){  
        System.out.println(fields[i].getType());  
        fieldNames[i]=fields[i].getName();  
    }  
    return fieldNames;  
   }  
     
   /** 
    * 获取属性类型(type),属性名(name),属性值(value)的map组成的list 
    * */  
   private List getFiledsInfo(Object o){  
    Field[] fields=o.getClass().getDeclaredFields();  
        String[] fieldNames=new String[fields.length];  
        List list = new ArrayList();  
        Map infoMap=null;  
    for(int i=0;i<fields.length;i++){  
        infoMap = new HashMap();  
        infoMap.put("type", fields[i].getType().toString());  
        infoMap.put("name", fields[i].getName());  
        infoMap.put("value", getFieldValueByName(fields[i].getName(), o));  
        list.add(infoMap);  
    }  
    return list;  
   }  
     
   /** 
    * 获取对象的所有属性值,返回一个对象数组 
    * */  
   public Object[] getFiledValues(Object o){  
    String[] fieldNames=this.getFiledName(o);  
    Object[] value=new Object[fieldNames.length];  
    for(int i=0;i<fieldNames.length;i++){  
        value[i]=this.getFieldValueByName(fieldNames[i], o);  
    }  
    return value;  
   }

The above is the detailed content of How to understand how to obtain object attribute types, attribute names, and attribute values ​​in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn