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

后端 未结 4 1856
难免孤独
难免孤独 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条回答
  •  甜味超标
    2021-01-21 20:20

    There could be many ways to achieve what you need. Though i would be interested in why you need.

    1. Override the toString() method.

      see: http://www.javapractices.com/topic/TopicAction.do?Id=55

    2. If the generation algorithm gets too long, then consider a separate class say UserPrettyPrinter.

      public interface UserPrettyPrinter {
        string print(User);
      }
      
      public class PrintUserInJSON implements UserPrettyPrinter {
        string print(User user) {
          //implement the algo here
        }
      }
      

      you can also implement:

      public class PrintUserInXML implements UserPrettyPrinter {
        string print(User user) {
          //implement the algo here
        }
      }
      
    3. Either in conjugation to number-2 or as a standalone class, you can write

      public class PrintObjectBasicAlgo {
        String print(Object obj) {
          /* i write pseudo code here. just ask if you cannot implement this
          this would help: http://docs.oracle.com/javase/tutorial/reflect/class/classMembers.html
      
          Class class = Obj.getClass();
      
          Filed[] allVariables = class.getAllFieldsByReflection();
      
          ArrayList keys = new ArrayList;
          ArrayList values = new ArrayList;
      
          for(Field field : allVariables) {
              Object value = reflectionGetValueOfField( field, obj );
              keys.add( field.getName());
              values.add(value.toString());
          }
      
          now that you have the keys and values, you can generate a string in anyway you like
      
          */
        }
      }
      
    4. You may see Visitor Pattern. it might be helpful.

提交回复
热议问题