Ask Questions and Find Answers
Important:
Ask is now read-only. You can review any existing questions and answers, but not add anything new.
But - don't panic! While ask is no more, we've replaced it with discuss - the new Liferay Discussion Forum! Read more here here or just visit the site here:
discuss.liferay.com
RE: RE: Service tracker java.lang.ClassCastException issue
Hi 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.
Whenever 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.
Hi Olaf,
Thanks for the answer. After changing the API from compile to compileOnly solved my problem.
Powered by Liferay™