How to insatiate instance of class from external jar in Tomcat Webapp

67 Views Asked by At

Basically our code allows people to pass in a custom implementation of our IRepository interface if they want to define their own repository for the files we generate. I keep getting the following error:

ClassCastException: S3RepositoryPlugin.S3Repository cannot be cast to package_name.IRepository

This is how I define the S3Repository:

public class S3Repository implements IRepository 

And this is how im trying to insatiate it:

URL[] urls = { new URL("jar:file:" + assembly +"!/") };
URLClassLoader cl = URLClassLoader.newInstance(urls);
Class classToLoad = Class.forName(className, true, cl);
IRepository externalRepo = (IRepository) classToLoad.newInstance();

Where assembly is the full path to the jar, and className is "S3RepositoryPlugin.S3Repository".

Any idea as to why this is happening? From the stuff Im seeing online it seems casting to interfaces works differently than casting to classes but im not sure if the code im using is necessarily affected by that.

NOTE: Using Tomcat9 and java8

1

There are 1 best solutions below

0
zaidabuhijleh On

I had to add the following code to the URLClassLoader to make it work:

URLClassLoader cl = URLClassLoader.newInstance(urls, getClass.getClassLoader());