场景:
java通过反射方式根据对象属性名称获取属性值
1.实现方法
public static Double getFieldValueByFieldName(String fieldName,Object object) {
try {
Field field = object.getClass().getDeclaredField(fieldName);
//对private的属性的访问
field.setAccessible(true);
return (Double) field.get(object);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
2.实体对象
public class DemoModel implements Serializable{
private static final long serialVersionUID = 6428876123605652053L;
private long id;
private String type;
private double z;
private double z1;
private double z2;
private double z3;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getZ() {
return z;
}
public void setZ(double z) {
this.z = z;
}
public double getZ1() {
return z1;
}
public void setZ1(double z1) {
this.z1 = z1;
}
public double getZ2() {
return z2;
}
public void setZ2(double z2) {
this.z2 = z2;
}
public double getZ3() {
return z3;
}
public void setZ3(double z3) {
this.z3 = z3;
}
}
3.测试main方法
public static void main(String []args){
System.out.println("测试开始");
DemoModel model = new DemoModel();
model.setId(12345678);
model.setType("01");
model.setZ(1111.2222);
model.setZ1(3333.4444);
model.setZ2(5555.6666);
model.setZ3(7777.8888);
for(int i=1;i<4;i++){
System.out.println("z"+i+ "=" + getFieldValueByFieldName(("z"+i),model));
}
System.out.println("测试结束");
}
4.结果展示
以上,TKS.