知道属性名称,可以用java 反射机制动态获取属性值
public class People {
private String name;
private Integer age;
/* 省略getter and setter*/
}
public class JavaReflectTest {
public static void main(String[] args) {
People people = new People();
people.setName("dgq");
people.setAge(26);
try {
Field field = people.getClass().getDeclaredField("name");
field.setAccessible(true);
System.out.println(field.get(people));
} catch (Exception e) {
e.printStackTrace();
}
}
}
如果是用groovy 就特别简单了
class People {
String name;
Integer age;
}
class ReflecTest {
public static void main(String[] args) {
People people = new People()
people.name = "dgq"
people.age = 26
println(people.getProperty("name"))
String property = "age";
println(people."$property")
}
}
网友评论