Java toString()使用反射? [英] Java toString() using reflection?
问题描述
前几天,我是通过手动将类的每个元素写到String中来为Java中的类编写toString()的,我想到使用反射可以创建通用的toString()方法可以在所有类上使用.IE.它将找出字段名称和值,并将其发送到字符串.
I was writing a toString() for a class in Java the other day by manually writing out each element of the class to a String and it occurred to me that using reflection it might be possible to create a generic toString() method that could work on ALL classes. I.E. it would figure out the field names and values and send them out to a String.
获取字段名称非常简单,这是同事想出的:
Getting the field names is fairly simple, here is what a co-worker came up with:
public static List initFieldArray(String className) throws ClassNotFoundException {
Class c = Class.forName(className);
Field field[] = c.getFields();
List<String> classFields = new ArrayList(field.length);
for (int i = 0; i < field.length; i++) {
String cf = field[i].toString();
classFields.add(cf.substring(cf.lastIndexOf(".") + 1));
}
return classFields;
}
使用工厂,我可以通过在第一次调用toString()时存储一次字段来减少性能开销.但是,找到这些值可能要昂贵得多.
Using a factory I could reduce the performance overhead by storing the fields once, the first time the toString() is called. However finding the values could be a lot more expensive.
由于反射的作用,这可能比实际还要假想.但是我对反射的想法以及如何使用它来改善我的日常编程很感兴趣.
Due to the performance of reflection this may be more hypothetical then practical. But I am interested in the idea of reflection and how I can use it to improve my everyday programming.
推荐答案
Apache commons-lang ReflectionToStringBuilder does this for you.
import org.apache.commons.lang3.builder.ReflectionToStringBuilder
// your code goes here
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
这篇关于Java toString()使用反射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!