Serialize a Java object to Java code?

后端 未结 5 2084
轻奢々
轻奢々 2020-12-31 14:03

Is there an implementation that will serialize a Java object as Java code? For example, if I have the object

Map m = new Map

        
5条回答
  •  -上瘾入骨i
    2020-12-31 14:48

    I had a similar problem recently and the little framework testrecorder evolved from it. It does also support objects not complying to the Java Bean Conventions. Your example be serializable like this:

    Map m = new HashMap();
    m.put("bar",new Integer(21));
    
    CodeSerializer codeSerializer = new CodeSerializer();
    System.out.println(codeSerializer.serialize(m)); // of course you can put this string to a file output stream
    

    and the output would be:

     HashMap map1 = new LinkedHashMap<>();
     map1.put("foo", 21);
    

    One may call serialize(Type, Object) to make map1 a more generic Type (e.g. Map or Map).

提交回复
热议问题