can't cast to implemented interface

浪子不回头ぞ 提交于 2019-11-27 01:57:00

This can happen if two different classloaders load a class named AutocompleteResult.

These two classes are then treated as entirely different classes, even if they have the same package and name (and even implementation/fields/methods).

A common cause for this is if you use some kind of plugin system and both your base classes and the plugin classes provide the same class.

To check for this issue print the value returned by Class.getClassLoader() on both offending classes (i.e. the class of the interface implemented by Device and the result of AutocompleteResult.class).

AKA when Java apparently doesn't Java.

I hit this problem recently with Play Framework 2.6.3, what helped me was this: https://www.playframework.com/documentation/2.6.x/ThreadPools#Application-class-loader

I leave this info here for the people that might have the same problem.

To make it clearer, what helps is:

Injecting Application on an Eager Singleton and then using its classloader to load the classes I was having issues with.

To make it clearer

public class Module {


 @Override
 public void configure {
   bind(TheClassLoaderLoader.class).asEagerSingleton()

public static class TheClassLoaderLoader {
  @Inject
        public TheClassLoaderLoader( Application application) {

         ClassLoader classloader = application.classloader();

                Class<?> interfaceClass = classloader.loadClass(InterfaceClass.class.getName());
                classloader.loadClass(ImplementsInterfaceClass.class.getName()).asSubclass(interfaceClass);

The example here https://playframework.com/documentation/2.6.x/JavaDependencyInjection#Configurable-bindings

That uses Environment often throws a frustrating ClassNotFoundException

Cheers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!