将加载的类保存到文件中

3

是否可以将已加载的类保存到文件中?

Class cc = Class.forName("projects.implementation.JBean");

或者,也许是为了获取该类的物理位置?
2个回答

1

可以的,因为Class.class实现了Serializable接口,所以你可以将它序列化到文件中,然后再进行反序列化。

例如 -

Class Test{
    public static void main(String[] args) throws ClassNotFoundException {
        try {
            OutputStream file = new FileOutputStream("test.ser");
            OutputStream buffer = new BufferedOutputStream(file);
            ObjectOutput output = new ObjectOutputStream(buffer);
            try {
                Class cc = Class.forName("com.test.Test");
                System.out.println(cc);
                output.writeObject(cc);
            } finally {
                output.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        try {
            // use buffering
            InputStream file = new FileInputStream("test.ser");
            InputStream buffer = new BufferedInputStream(file);
            ObjectInput input = new ObjectInputStream(buffer);
            try {
                // deserialize the class
                Class cc = (Class) input
                        .readObject();
                // display 
                System.out.println("Recovered Class: " + cc);
            } finally {
                input.close();
            }
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }
    }

我不这么认为。它会像任何其他序列化一样。 - Subhrajyoti Majumder
1
输出文件已损坏,我没有收到错误提示,但它的大小只有258字节,我无法加载或反编译它。 - markiz
我真的很惊讶,这里运行得很好。我想问一下你使用的是哪个JDK? - Subhrajyoti Majumder

0

在Java中,将类对象序列化只序列化了类的限定名称。当反序列化时,通过名称查找该类。

一般情况下,我认为一旦加载了类定义(字节码),就不可能获取相应的字节。Java允许在运行时定义类,并且据我所知,在类加载后不会公开这些字节。

但是,根据使用的ClassLoader,您可能会发现

cc.getResourceAsStream("JBean.class")

你所需要的就是使用自己的ClassLoader将类流作为资源加载。

另一个选择是拦截类的加载。ClassLoader将在“defineClass”中看到字节,因此自定义的ClassLoader可以将它们存储在某个地方。


请问您能解释一下“拦截类的加载”是什么意思吗? - markiz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接