今天我一同事有一问题:他有一个po,里面有上百个属性,现在他需要根据用户勾选上的来返显到前台,且以后属性还会增加。
若po中只有几个属性,我们可以只用if/else判断来做这个功能;但在他这里这么写就有点难受了,所以考虑用反射来实现这个功能。
1、创建一个Student:
class Student{
String name;
int age;
int height;
int weight;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
2、反射类
private static <T> void getFunctionByClass(T require,String functionName){
Class re= require.getClass();
try {
Field field = re.getDeclaredField(functionName);
System.out.println("field:"+field);
System.out.println(field.get(require));//调用对象的方法
} catch (Exception e) {
e.printStackTrace();
}
}
3、main函数
public static void main(String[] args){
Student a1=new Student();
a1.setName("Li Ming");
a1.setAge(18);
a1.setHeight(180);
a1.setWeight(90);
getFunctionByClass(a1,"name");
}