0

in Tomcat 7, I need to load in a class from a specific jar in the war file, in /WEB-INF/lib/jasperreports-5.6.0.jar.

How can I get the following code to work?

The jar contains the class indicated but I apparently don't know how to properly qualify the jar in the first line so that it is found

URL[] classLoaderUrls = new URL[]{new URL("file://WEB-INF//lib//jasperreports-5.6.0.jar")};
URLClassLoader urlClassLoader = new URLClassLoader(classLoaderUrls);
Class<?> beanClass = urlClassLoader.loadClass("net.sf.jasperreports.engine.JasperRunManager");
draca
  • 1,319
  • 5
  • 16
  • 32
  • 1
    Just an observation: For Tomcat (including version 7), classes in JAR files in your web application's `/WEB-INF/lib` directory should already be visible to your webapp. Sounds like maybe something else is going on, if you need to code for this? – andrewJames Aug 04 '20 at 19:35
  • @andrewjames Well actually, the tomcat lib folder has an older version of that jar, which has to be there, so I need to override that and explicitly declare that this project is to use the classes in the war file (WEB-INF/lib). Right now my project finds and uses the classes in the older jar – draca Aug 04 '20 at 21:14
  • OK - thanks for clarifying. What you describe is not the standard Tomcat behavior. Normally, Tomcat looks in your web app's `/WEB-INF/lib` for classes in JARs _before_ it looks in `CATALINA_HOME/lib`, or `CATALINA_BASE/lib` (as [described here](https://tomcat.apache.org/tomcat-7.0-doc/class-loader-howto.html) for your version of Tomcat). See the section starting _"Therefore, from the perspective of a web application..."_. – andrewJames Aug 04 '20 at 21:19
  • The only exception I know, is if Tomcat has been explicitly configured to change this order, by customizing the `loader` component (see [here](https://tomcat.apache.org/tomcat-7.0-doc/config/loader.html)). To be honest, I have never seen anyone use that. – andrewJames Aug 04 '20 at 21:20
  • Regardless of Tomcat's default behavior, I should be able to code around that with the 3 line classloader code that I posted, but I get a ClassNotFoundException so something is wrong with my code. How can I fix my code? – draca Aug 05 '20 at 14:29
  • JAR file URLs have their own [specific format](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/net/JarURLConnection.html): `jar:!/{entry}`. The examples use `jar:http:...` - but I assume yours would need to be `jar:file:...`. Also, you don't need those double-forward slashes `//` as path segment separators - just one `/`. – andrewJames Aug 05 '20 at 15:01
  • Example: [How to load Classes at runtime from a folder or JAR?](https://stackoverflow.com/questions/11016092/how-to-load-classes-at-runtime-from-a-folder-or-jar) – andrewJames Aug 05 '20 at 15:14

0 Answers0