我有POJO课程
Class Book {
private String id;
private String title;
Public Book() {
}
//implement setter and getter
..............
}
main() {
Book book = new Book();
book.setId(1);
book.setTitle("new moon");
}如何获得图书对象的所有实例变量--我希望结果变成-> 1,“新月”--而不用getter方法,这样我就可以转换另一个POJO对象。
澄清:
我有两个班
Book {
String id;
String title;
//constructor
//setter
}
Student {
String id;
String name;
//cuonstructor
//setter
}
main() {
Book book = new Book();
book.setId(1);
book.setTitle("new moon");
Student student = new Student();
student.setId(1);
student.setName("andrew");
//suppose i have BeanUtil object to get all instance varable value and class meta data
BeanUtil.getMetadata(book, Book.class);
//output is
//id, title
//suppose i have BeanUtil object to get all instance varable value and class meta data
BeanUtil.getMetadata(student, Students.class);
//output is
//id, name
BeanUtil.getInstanceVariableValue(student, Student.class);
//output
//1, andrew
BeanUtil.getInstanceVariableValue(book, Book.class);
//output
//1, new moon
}发布于 2009-12-08 03:39:20
我通常使用PropertyUtils,这是BeanUtils的一部分。
//get all of the properties for a POJO
descriptors = PropertyUtils.getPropertyDescriptors(book);
//go through all values
Object value = null;
for ( int i = 0; i < descriptors.length; i++ ) {
value = PropertyUtils.getSimpleProperty(bean, descriptors[i].getName())
}
//copy properties from POJO to POJO
PropertyUtils.copyProperties(fromBook, toBook);发布于 2009-12-08 03:37:00
如果要获取Book实例的所有属性的值,可以使用反射进行此操作。但是,这需要大量的代码,而且代价很高。一个更好的方法是(IMO)简单地实现一个getAllValues()方法:
public Object[] getAllValues() {
return new Object[]{this.id, this.title};
}或者更好的是,让它填充并返回Map或Properties对象。我想这取决于你的用例,哪个更好。(虽然我很难理解为什么需要数组/列表中所有属性的值.)
发布于 2009-12-08 04:26:19
这个怎么样:
public static String getMetadata(Class input) {
StringBuffer result = new StringBuffer();
// this will get all fields declared by the input class
Field[] fields = input.getDeclaredFields();
for (int i=0; i<fields.length; i++) {
if (i > 0) {
result.append(", ");
}
field[i].setAccessible(true);
result.append(field[i].getName());
}
}
public static String getInstanceVariableValue(Object input) {
StringBuffer result = new StringBuffer();
// this will get all fields declared by the input object
Field[] fields = input.getClass().getDeclaredFields();
for (int i=0; i<fields.length; i++) {
if (i > 0) {
result.append(", ");
}
fields[i].setAccessible(true);
result.append(fields[i].get(input));
}
return result;
}我没有尝试编译或运行它,所以让我知道它是如何进行的。
https://stackoverflow.com/questions/1864300
复制相似问题