Print whole structure with single call (like JSON.stringify) in Java?

后端 未结 4 1819
难免孤独
难免孤独 2021-01-21 19:49

How to print any class instance in Java? Similar to JSON.stringify() in Javascript. Not necessary JSON, any format of output will do.

public class User {
    pub         


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-21 20:07

    You have two options here. The simple one is just to override the toString function for your class. I dont see why you dont do this really. In this case its as simple as

    String toString(){
        return "{ name:\""+name+", password: \""+passowrd....
    }
    

    The second option is to use reflection. This would be slightly (though not really) better if you had some sorta external class used for "printing classes". The pseudo code for that would be

    StringBuilder s = new StringBuidler();
    for(Field f : fields){
        s.append(f.getName() + "\" :\"" + f.get()+ "\"");
    }
    return s.toString();
    

    However this would be costly as reflection always is. Also if you just properly override the toString functions in the first place your printClass function could literally just be

    String printClass(Object o){ return o.toString();}
    

    Which of course again begs the question of why do you need a printClass function?

提交回复
热议问题