其中用的到了java.lang.reflect包下的feild、method类。实现对实体的属性进行遍历。
测试遍历类:
public class testEntity {
public static void main(String[] args) {
Entity entity=new Entity(1, "测试实体", "遍历实体");
testEntity test=new testEntity();
test.iterateEntity(entity);
}
public void iterateEntity(Entity entity){
Field[] fields=entity.getClass().getDeclaredFields();//获取实体的所有属性
String type = field.getGenericType().toString(); //获取属性的类型
for(Field field:fields){
Method m;
String name=field.getName();//获取属性名
// System.out.println("name:"+name);
try {
m = entity.getClass().getMethod("get"+toUpperCaseFirstOne(name));//调用get方法获取属性值(注意这里属性名首字母记得转为大写)
System.out.println(name+":"+m.invoke(entity)+":"+type);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//首字母转小写
public static String toLowerCaseFirstOne(String s)
{
if(Character.isLowerCase(s.charAt(0)))
return s;
else
return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
}
//首字母转大写
public static String toUpperCaseFirstOne(String s)
{
if(Character.isUpperCase(s.charAt(0)))
return s;
else
return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
}
}
测试实体:
class Entity{
private int id;
private String name;
private String content;
Entity(int id,String name,String content){
this.id=id;
this.name=name;
this.content=content;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
打印出的结果:
id:1:int
name:测试实体:class java.lang.String
content:遍历实体:class java.lang.String