Serialize a Java object to Java code?

后端 未结 5 2058
轻奢々
轻奢々 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条回答
  • 2020-12-31 14:42

    I implemented this functionality in a new github project. You can find the project here:

    https://github.com/ManuelB/java-bean-to-code-serializer

    The project does not have any external dependencies except junit.

    Currently it is not supporting arrays for serialization yet. Nevertheless there is already a lot of functionalities:

            Object2CodeObjectOutputStream object2CodeObjectOutputStream = new Object2CodeObjectOutputStream(
                byteArrayOutputStream);
            object2CodeObjectOutputStream.writeObject(<your-java-bean>);
            System.out.println(
                    byteArrayOutputStream.toString());
    
    0 讨论(0)
  • 2020-12-31 14:45

    The pre-release of Long Term Persistence (java.beans.Encoder and friends) had both an XMLEncoder and a Java encoder. You can probably still download it somewhere.

    0 讨论(0)
  • 2020-12-31 14:46

    Could you use Clojure instead and integrate it with your Java code? Clojure is homoiconic - its data is identical to its code, so you can do things like this very easily.

    Maps are a basic datatype in Clojure.

    0 讨论(0)
  • 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<String,Integer> m = new HashMap<String,Integer>();
    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<String, Integer>).

    0 讨论(0)
  • 2020-12-31 15:08

    You can achieve custom serialization of your objects. You have to implement two methods in your class with the exact signature:

    private void writeObject(ObjectOutputStream oos)
    {
        //write your serialization code here
    }
    
    
    private void readObject(ObjectInputStream ois)
    {
        //write your de-serialization code here
    }
    

    However the amount of flexibility that you are seeking is very doubtful.

    0 讨论(0)
提交回复
热议问题