diana.diaconu
diana.diaconu

Reputation: 11

Load library jars with javassist

I am trying to analyze the code of a java project. I have the project to be analyzed in a jar that I add to javassist path using insertClassPath function. Everything works fine if I try to access a class form the project. The problem is that I need to access also the classes from the libraries the project uses.

I tried to add the library to the class path just like i did with the project jar, but I get a NotFoundException so i guess I am not giving the right path.

The code looks like this:

String jarFileName = "C:/Users/diana/Desktop/Test/ckjm.jar";
ClassPool pool = ClassPool.getDefault();
    try{
        pool.insertClassPath(jarFileName);
        pool.insertClassPath("C:/Users/diana/Desktop/Test/ckjm/lib/bcel-5.2.jar");
    } catch (NotFoundException e) {
        System.out.println("error loading jar!!");
    } 

I used the harcoded string just for testing purpose. The jar is in the lib folder or the project that was archived to a jar. I am not sure how can i add a jar that is contained in another jar.

Note: if i keep the library as a separate jar (and give the path like: "C:/Users/diana/Desktop/Test/bcel-5.2.jar") it woks fine

Any help would be appreciated

Upvotes: 1

Views: 1450

Answers (1)

Nicholas
Nicholas

Reputation: 16066

If your target JAR is inside another JAR, you can use a LoaderClassPath created using a URLClassLoader which is defined using a JarURLConnection URL path of the JAR.

So assume you have a target JAR, inner.jar, embedded inside another JAR, C:/Users/diana/outer.jar.

Let's assume it is in a subdirectory called lib.

The URL of the outer JAR would be file:/C:/Users/diana/outer.jar.

The URL of the inner JAR would be jar:file:/C:/Users/diana/outer.jar!/lib/inner.jar.

You code to load this classpath would be:

URL cpUrl = new URL("jar:file:/C:/Users/diana/outer.jar!/lib/inner.jar");
URLClassLoader cpUrlLoader = new URLClassLoader(new URL[]{cpUrl});
pool.insertClassPath(new LoaderClassPath(cpUrlLoader));

Upvotes: 0

Related Questions