简体   繁体   中英

Java - How can I dynamically instantiate an abstract class from a JAR?

I'm trying to use Javassist to load an abstract method class that is dynamically loaded from a JAR file at runtime. For some reason, this code only runs on the Windows operating system. I get a ClassDefNotFoundException on any other platform. This is the code I used.

public static void example() throws Exception {
    String pathToJar = "pathToJar.jar";
    File JARFile = new File(pathToJar);
    ClassLoader classLoader = URLClassLoader.newInstance(new URL[]{ JARFile.toURI().toURL() });
    Class<?> callBackClass = classLoader.loadClass("package.Callback");

    ProxyFactory factory = new ProxyFactory();
    factory.setSuperclass(callBackClass);
    MethodHandler handler = new MethodHandler() {

        @Override
        public Object invoke(Object self, Method overridden, Method forwarder,
                Object[] args) throws Throwable {
            return forwarder.invoke(self, args);
        }
    };

    factory.setFilter(
            new MethodFilter() {
                @Override
                public boolean isHandled(Method method) {
                    return Modifier.isAbstract(method.getModifiers());
                }
            }
            );
    Object instance = factory.create(new Class<?>[0], new Object[0], handler); /*exception thrown here on non-windows OS*/
}

Is this a problem with the class loader? Or is it a problem with Javassist? It's supposed to be platform independent, but depending on the OS, it may or may not run.

exception thrown here on non-windows OS

That's a big clue, suggesting that there's a capitalization difference somewhere. The major file systems used with Windows are case-insensitive, whereas the major file systems used elsewhere (*nix) are case-sensitive. So look very carefully at the capitalization of the resources you're trying to load and ensure what you're loading has exactly the same capitalization in your code as it does in the jar or in the file system.

The class that cannot be found and causes the exception is

javassist.util.proxy.ProxyObject

Are you sure that you have the correct jar on your class path on the non-Windows OS? The proxy object interface is implemented by any class that javassist creates. It seems to not being visible to the class loader. Did you try to define an explicit class loader provider ?

I agree with the other answer that casing is the most probable cause. Can you provide the command with that you run the application and the exact file names of the jars?

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