Java toString() using reflection?

后端 未结 7 1629
梦如初夏
梦如初夏 2020-12-02 18:30

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 mig

7条回答
  •  生来不讨喜
    2020-12-02 18:36

    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);
    }
    

提交回复
热议问题