Java toString() using reflection?

后端 未结 7 1632
梦如初夏
梦如初夏 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:35

    Another option, if you are ok with JSON, is Google's GSON library.

    public String toString() {
        return new GsonBuilder().setPrettyPrinting().create().toJson(this);
    }
    

    It's going to do the reflection for you. This produces a nice, easy to read JSON file. Easy-to-read being relative, non tech folks might find the JSON intimidating.

    You could make the GSONBuilder a member variable too, if you don't want to new it up every time.

    If you have data that can't be printed (like a stream) or data you just don't want to print, you can just add @Expose tags to the attributes you want to print and then use the following line.

     new GsonBuilder()
    .setPrettyPrinting()
    .excludeFieldsWithoutExposeAnnotation()
    .create()
    .toJson(this);
    

提交回复
热议问题