Java toString() 使用反射? [英] Java toString() using reflection?

查看:16
本文介绍了Java toString() 使用反射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前几天我正在为 Java 中的一个类编写一个 toString(),通过手动将类的每个元素写出到一个 String 中,我突然想到使用反射可能会创建一个通用的 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 为你做这件事.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆