简体   繁体   中英

Dynamically load a class and its object in java

I have a class file and a saved object of that class. My java application doesn't have that class in its libraries. When I tried to load the object using ObjectInputStream , it gives an ClassNotFoundException .

Then I use the following code.

 URLClassLoader classLoader = new URLClassLoader(new URL[]{classFile.getParentFile().toURI().toURL()});
 classLoader.loadClass(classFile.getName().replace(".class", "")).newInstance();
 myClass= (MyClass) FileIOManager.readObject(classObj);

But this code also gives me the same exception when reading the object. Hope for a help to do my task..

MyClass doesn't have a package name.

FileIOManager.readObject() is a method I created to read a object and it works fine for other object which have classes inside my libraries.

I changed the readObject() method in FileIOManager class that I created to the following..

public static Serializable readObject(String path) throws FileNotFoundException, IOException, ClassNotFoundException {
    return readObject(path, null);
}

public static Serializable readObject(String path, final ClassLoader classLoader) throws FileNotFoundException, IOException, ClassNotFoundException {
    Serializable obj;
    try (FileInputStream fis = new FileInputStream(path); ObjectInputStream ois = new ObjectInputStream(fis) {

        @Override
        protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
            if (classLoader == null) {
                return super.resolveClass(desc);
            }
            return Class.forName(desc.getName(), false, classLoader);
        }

    }) {
        obj = (Serializable) ois.readObject();
    }
    return obj;
}

Here path is the path to the class file.

And get the object as follows.

URLClassLoader classLoader = new URLClassLoader(new URL[]{classFile.getParentFile().toURI().toURL()});
myClass = (MyClass) FileIOManager.readObject(loc, classLoader);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM