Message Boards
Service tracker java.lang.ClassCastException issue
Service tracker java.lang.ClassCastException issue
New Member Posts: 4 Join Date: 2/3/21 Recent PostsHi Guys,
I Have created some custom OSGi API and Services using API and Service template on LDS. When I inject the service in OSGi liferay MVC module is working properly. But when I am trying to access it in Spring MVC portlet it is not working. As per Liferay's documentation we can use service tracker for accessing OSGi service in Spring MVC portlets. But when I try to inject Service using service tracker I am getting below exception.
java.lang.ClassCastException: class
com.se.theexchange.commons.services.impl.IDMSServiceImpl cannot be
cast to class com.se.theexchange.commons.services.api.IDMSService
(com.se.theexchange.commons.services.impl.IDMSServiceImpl is in
unnamed module of loader
org.eclipse.osgi.internal.loader.EquinoxClassLoader @7d61d943;
com.se.theexchange.commons.services.api.IDMSService is in unnamed
module of loader org.eclipse.osgi.internal.loader.EquinoxClassLoader @308c744b)
Below is the code snippet:
Bundle bundle = FrameworkUtil.getBundle(this.getClass());
BundleContext bundleContext = bundle.getBundleContext();
ServiceTracker<IDMSService, IDMSService> serviceTracker =
new ServiceTracker(bundleContext, IDMSService.class,
null);
@RenderMapping(params =
"javax.portlet.action=success")
public String
showGreeting(ModelMap modelMap) throws InterruptedException{
serviceTracker.open();
if(!serviceTracker.isEmpty()) {
System.out.println(":::Test Message:::
"+serviceTracker.waitForService(500).testidmsService());
}else {
System.out.println(":::::::::service not
found:::::::::");
}
}
I am using Liferay DXP 7.3 sp2 bundle.
RE: Service tracker java.lang.ClassCastException issue (Answer)
Liferay Legend Posts: 6403 Join Date: 9/23/08 Recent PostsWhenever you can't typecast an object to a legitimate superclass or interface, you're dealing with multiple instances of the superclass/interface on the classpath. So, your "object AA" is a of a subclass of "Interface A loaded by classloader X", but you're trying to cast to "Interface A loaded by classloader Y".
Unfortunately the error message omits the classloader part (well, here it's attempting to do so, but it's not very clear)
The solution? Make extra extra extra sure that you have only one instance of the interface in your runtime. E.g. never compileInclude an API, never copy interfaces or classes - especially exported ones - into other projects.
RE: RE: Service tracker java.lang.ClassCastException issue
New Member Posts: 4 Join Date: 2/3/21 Recent PostsHi Olaf,
Thanks for the answer. After changing the API from compile to compileOnly solved my problem.