可以使用Java的反射API来根据键名获取对象的键值。以下是一个示例代码:
import java.lang.reflect.Field;
public class Example {
public static void main(String[] args) {
MyObject obj = new MyObject();
obj.firstName = "John";
obj.age = 30;
obj.lastName = "Doe";
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true); // 允许访问私有字段
Object value = field.get(obj);
System.out.println(field.getName() + ": " + value);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
class MyObject {
private String firstName;
private int age;
private String lastName;
}