获取Java对象中所有的属性名称和属性值
1,首先我们创建一个Java实体类Person,并创建属性name,age,gender,代码如下:
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; } }
2、创建对象
Person person = new Person("zhangsan", 30, "男");
3、创建获取属性数组的方法
/** * 获取属性名数组 * */ 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; }
4,根据属性名称获取对应的属性值(通过get方法)
/* 根据属性名获取属性值 * */ 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; } }
5、完美调用
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());
6、打印结果:
attribute name:name/age/gender attribute value:zhangsan/30/男