java


ClassCastException Error while dynamically loading classes from a JAR file outside WAR at run time in JAVA?


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();
}
}

Related Links

Spring application can't retrieve data from property source
Why is the jframe not being cleared?
Failed to crunch file - Android studio (app:mergeDebugResources)
Best way to create a dynamic template with dynamic data base
Storing value in another class
Android Can't get display but found hdmi connected
Action at pressing the key on certain line in jlist
How to connect Pentaho to Oracle RAC
400 Bad request on a POST service
Why isn't my JUnit test for a file's existence working?
Java for-loop not iterating, stops the method after one iteration rather than repeating
How to specify JedisConnectionFactory instance for RedisHttpSessionConfiguration initialization
Expose Adobe AEM bundles as restful webservices
ClassNotFoundException while switching to STS 3.8.3 [duplicate]
How to use StringToWordVector (weka) in java?
How to get a reference to a file

Categories

HOME
compiler-construction
testing
openstack
activiti
path-finding
relative-path
fme
objectgears
sqlite-net-extensions
sharepoint-designer
jpeg
win32gui
windows-server
indesign
correlation
collectd
jsdoc
reactive-cocoa
database-replication
code-review
java-3d
cultureinfo
crosstab
poltergeist
linkerd
minitab
primitive
uisplitview
semantic-versioning
contact-form
code-contracts
stringtemplate
xmlreader
libvpx
az-application-insights
galen
ibpy
keydown
mime
unixodbc
acoustics
apple-news
cubic-spline
tropo
namecoin
epson
google-feed-api
instant
rotativa
savon
transmitfile
nsfilemanager
ctest
autorest
websitepanel
actionbardrawertoggle
master-slave
nessus
associative-array
netmq
browser-link
ionic
unity3d-gui
ami
tt-news
rdtsc
preferences
typeof
gridfs
easy-install
limejs
pendrive
invite
self-extracting
propagation
visitor-statistic
gallio
mozilla-prism
premature-optimization

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App