I wanted to dynamically load jar files (and its classes) in my war code.
To do this I have written my object factory class as such:
import java.io.File;
import java.net.*;
public class ObjectFactory {
private ClassLoader cl;
public ObjectFactory(String jarFilePath) {
try {
File file= new File(jarFilePath);
URL url = file.toURL();
URL[] urls = new URL[]{url};
cl = new URLClassLoader(urls);
} catch (Exception e) {
e.printStackTrace();
}
}
public <T> T getObject(String id){
try {
Class cls = cl.loadClass(id);
T object =(T)cls.newInstance();
return object;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
I have a Duck interface:
public interface Duck {
public String quack(String arg);
}
And I have created service class to get Ducks I want at runtime:
public class DuckServiceClass {
public static Duck getDuck(){
try {
String jarFilePath="\path\to\my\external_jar.jar"
ObjectFactory of = new ObjectFactory(jarFilePath);
Duck d1=of.getObject("implementationOfDuck.RobotDuck");
return d1;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
My jar has a copy of Duck interface and has various implementation of Duck : for example RobotDuck class:
package implementationOfDuck;
import Duck;
public class RobotDuck implements Duck {
@Override
public String quack(String arg) {
return "Q U A N C K!!!" +arg;
}
}
This service class works all fine in a main method:
public class WebAppTest {
public static void main(String[] args) {
Duck d1 =DuckServiceClass.getDuck();
System.out.println(d1.getName()+">"+d1.quack("Hello"));
}
}
But If I refer this ServiceClass method in my jsp page it gives me :
java.lang.ClassCastException: implementationOfDuck.RobotDuck cannot be cast to Duck
My JSP page is :
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="Duck" %>
<%@ page import="DuckServiceClass" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Duck-O-Gram</title>
</head>
<body>
<%
Duck d1=DuckServiceClass.getDuck();
%>
<h1><%=d1.quack("Hello")%></h1>
</body>
</html>
can any one guide me how to resolve this issue in a webapp ?
As @JimGarrison said, Duck
is loaded by webapp class loader and URLClassLoader
twice.
Specified the parent class loader in constructor of URLClassLoader
could fix the problem. cl
will search class/resource using parent class loader first, then load class/resource from given URLs. Since Duck
is already loaded by webapp class loader, Duck.class
inside external_jar.jar will not be loaded again.
public ObjectFactory(String jarFilePath) {
try {
File file= new File(jarFilePath);
URL url = file.toURL();
URL[] urls = new URL[]{url};
cl = new URLClassLoader(urls, getClass().getClassLoader());
} catch (Exception e) {
e.printStackTrace();
}
}