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

How to separate methods from a java class [duplicate]
Removing punctuation marks in java
How to print two 2D double arrays?
Strange behaviour with ConnectionFactory using CDI with Tomcat 7
Android UnityPlayerActivity Action Bar
Native Error: [25037] - There is not enough disk space left for the Database (Windows Compact)
Retrieve data from Json through php in android?
Calculate time between dates in list
Java= arbitrary placement of if statement gives different output? [duplicate]
Do Orphaned object in java lead to performance Issues [duplicate]
How do I mock an object of a class with parameterized constructor?
How to concatenate strings in Java?
How can I convert java.util.Calendar to org.quartz.impl.calendar.DailyCalendar?
Lose focus when user clicks outside Node's bound in JavaFX
Parallel Stream gives null items, How to do in Java 8
Extending the ObjectFactory in EclipseLink MOXy

Categories

HOME
wso2
mediawiki
json.net
view
onedrive
session
electron
spagobi
framework7
elm
cross-browser
ezpublish
medical
awesome-wm
fancybox-3
izpack
offline
quicklook
http-status-code-504
undefined
openedx
grails3
autocad-plugin
clickonce
tokenize
errorlevel
wkwebview
php-openssl
restful-authentication
pingfederate
atlassian-crucible
vision
bpel
flink-streaming
microsoft-chart-controls
fog
accelerate-framework
wallpaper
y86
normal-distribution
restlet
libvpx
occlusion
c11
document.write
ansible-playbook
dism
android-mediaprojection
import-from-excel
segment
scorm
flickr-api
hibernate-tools
theming
blogengine.net
nativeapplication
composite-key
crypt
windows-mobile-6.5
ado.net-entity-data-model
pcf
angstrom-linux
marching-cubes
browser-bugs
cisco-ios
key-management
csquery
jscript.net
qpainter
android-imagebutton
comexception
mysql-error-1062
rtmfp
message-driven-bean
mcts
terminal-services
mysqltuner
oam
commoncrypto
access-rights
apc
web2py-modules
sqlperformance
ocunit
quickdialog
errai
ticoredatasync
wse3.0
removeclass
hirefire
xmemcached
netbeans-7.1
celltable
visitor-statistic
wise
perfect-hash
memory-size
privilege
private-members
grid-system
wsdl.exe
rtml
lzh

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App