将Java对象序列化为Java代码? [英] Serialize a Java object to Java code?

查看:46
本文介绍了将Java对象序列化为Java代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在将Java对象序列化为Java代码的实现?例如,如果我有对象

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

Map<String,Integer> m = new Map<String,Integer>();
m.put("foo",new Integer(21));

我可以使用

ObjectOutputStream out = new ObjectOutputStream( ... );
out.writeObject( m );
out.flush();

例如,输出将是

java.util.Map<String,Integer> m = new java.util.Map<String,Integer>(); 
m.put("foo",new Integer(21));

为什么要这个?有时,以编程方式部分地创建复杂的对象,然后以代码手动完成创建会更容易。然后,可以将该代码包含在源代码中,并用其他所有版本控制版本。请注意,使用外部序列化的对象并不是不可缺少的。

Why would you want this? Sometimes it is easier to partially create complex objects programmatically and then complete the creation manually in code. This code can then be included in the source and version controlled with everything else. Note that using external serialized objects is not exceptable.

感谢您提供的任何帮助。

Thanks for any help you can give.

推荐答案

我在一个新的github项目中实现了此功能。您可以在这里找到项目:

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());

这篇关于将Java对象序列化为Java代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆