获取Java对象属性信息

2018/08/17 Java

初始化类对象

public class Person {
	private String name;
	private int age;
	private String gender;
	
	public Person(String n,int a,String g) {
		name = n;
		age = a;
		gender = g;
	}
	
	public String getName() {
		return name;
	}
	
	public int getAge() {
		return age;
	}
	public String getGender() {
		return gender;
	}
}

获取对象属性数组

    /**  
     * 获取属性名数组  
     * */  
    private static 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;  
    }  

获取属性数值


	/* 
		根据属性名获取属性值  
		*
   		*/  
    private static 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) {    
          
            return null;    
        }    
    } 

测试代码


		StringBuilder sbName = new StringBuilder();
		StringBuilder sbValue = new StringBuilder();
		String[] fieldNames = getFiledName(person);
		 
		  for(int j=0 ; j<fieldNames.length ; j++){     //遍历所有属性
	               String name = fieldNames[j];    //获取属性的名字
	               Object value = getFieldValueByName(name,person);
	               sbName.append(name);
	               sbValue.append(value);
	                if(j != fieldNames.length - 1) {
	                	sbName.append("/");
	                	sbValue.append("/");
	                }
	              
	              
	        }
	      
	        System.out.println("attribute name:"+sbName.toString()); 
	        System.out.println("attribute value:"+sbValue.toString()); 
	        

输出

attribute name:name/age/gender
attribute value:zhangsan/30/男

参考文章

获取Java对象中所有的属性名称和属性值

Search

    Table of Contents