markiz
markiz

Reputation: 2184

Save loaded class to a file

Is it possible to save a loaded class to a file?

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

Or, maybe to get the physical location of that class?

Upvotes: 3

Views: 1091

Answers (2)

Matt Hillsdon
Matt Hillsdon

Reputation: 71

Serializing a Class object in Java serializes little more than the qualified name of the class. When deserializing the class is looked up by name.

In the general case, I don't think it's possible to get the bytes corresponding to a class definition (the bytecode) once it has been loaded. Java permits classes to be defined at runtime and, so far as I'm aware, doesn't expose the bytes after the class has been loaded.

However, depending on the ClassLoader in use, you may find that

cc.getResourceAsStream("JBean.class")

is all you need, loading the class stream as a resource using its own ClassLoader.

Another option could be to intercept the loading of the class. The ClassLoader will get to see the bytes in "defineClass", so a custom ClassLoader could store them somewhere.

Upvotes: 0

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41230

Yes you can as Class.class implements Serializable interface you can serialize it into file and as well deserialize again.

Example -

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

    }
    }

Upvotes: 1

Related Questions