Java :(部分)类的序列化(不是对象!)
我目前正在执行一项任务,将一个组件及其依赖项打包在一起,并从中制作出一个包含所有需要的东西的独立组件。
I am currently working on a task to package a component and its dependencies together and makes a stand-alone component out of it that has all needed stuff included.
我遇到的情况是,我可能也需要在此组件中包含用户定义的类。
I have the situation that I might have user-defined classes which I need to include in this component, too.
我正在寻找一种以苗条/智能的方式序列化它们的方法。例如,这些类具有继承层次结构:
I am looking for a way to serialize them in a slim/smart way. These classes have a inheritance hierarchy for instance:
FrameWorkSuper
--------------
UserSuper
UserClass
是否有一种只能序列化User的方法类的定义部分,以保持较小的占地面积?任何源自框架的内容都绝对包含在最终组件中。因此,我想序列化并稍后仅加载整个用户定义的部分,以使类获得框架部分也在包中。
Is there a way to serialize only the User-defined part of a class to keep the footprint small? Anything that originates from the framework is definitely in the final component included. Thus I want to serialize and load later only the user-defined part of the whole in a way that the class gets that the framework part is also in the package.
是
我认为您想做的是
- 如果没有这些类的字节码,而只有源代码,则传输用户定义的类的实际字节码。 ,您需要先对其进行编译。我建议使用 JavaCompiler 。
- 由于将所有内容编译到磁盘然后再次将其读取到字节数组有点繁琐,因此您可能要使用自己的FileManager和JavaFileObject实现,如有必要,我可以提供有关此步骤的详细信息。
创建一个自定义的类加载器,该加载器获取所有类的字节码,并将其findClass方法覆盖为类似
Create a custom classloader which gets the byte code of all the classes and override its findClass method to something like
// first try our cache of loaded classes
if (loadedClasses.containsKey(name)) {
return loadedClasses.get(name);
}
// that didn't work, maybe the class was compiled but not yet loaded
if (compiledClasses.containsKey(name)) {
// get the representation from the cache
InMemoryClassJavaFileObject inMemoryRepresentation = compiledClasses.get(name);
// let our parent define the class
Class<?> clazz = defineClass(name, inMemoryRepresentation.getData(), 0, inMemoryRepresentation.getData().length);
// and store it in the cache for later retrieval
loadedClasses.put(name, clazz);
return clazz;
}
请注意,您不需要创建 InMemoryClassJavaFileObject
,您可以简单地使用字节数组。
Note that you do not need to create InMemoryClassJavaFileObject
, you can simply use a byte array.
这使您可以在远程站点*问类本身:您可以创建实例并使用其方法。
That gives you access to the class itself on the remote site: you can create instances and use their methods.