ClassCastException from a list of objects that implement the common interface

I have a list of classes that implement an interface IApplication

:

public interface IApplication {
    public void start();
}
public class Configurator implements IApplication {
    public void start() {...};
}

public static void main(String[] args) {
    List<IApplication> apps = new ArrayList<IApplication>();
    apps.add(new Configurator());

    apps.get(0).start(); //ClassCastException   
}

      

When the last line in my main function is executed, I get ClassCastException

:

java.lang.ClassCastException: Configurator cannot be cast to IApplication

      

Even if I instantiate the Configurator object as IApplication, I get the following error:

IApplication app = new Configurator();
app.start();

java.lang.IncompatibleClassChangeError: Class Configurator does not implement the requested interface IApplication

      

If this is not allowed in Java? Could this be an issue where my config class is not being updated correctly with the implementation? ClassCastException from a list of objects that implement the common interface

+3


source to share


1 answer


You seem to have two different interfaces loaded from different packages, both named IApplication

. In OSGI, classes (and interfaces, and enumerations, etc.) from different packages are always different, even if they have the same name and package name!

Configurator

implements an interface IApplication

from a package com.configurator-plugin

, whereas your method main

refers to an interface IApplication

from a package com.configuration-management-common

.



If they are supposed to be the same interface, you must remove it from one of those packages and make sure it exported from the other, and make sure that the package that exports the interface is a dependency of the package that it uses.

There is no easy way to specify which package to load the class or interfaces as the Java language has no concept of bundles to begin with. If they have to be two different interfaces, I suggest you make sure they have different names (and then the problem should be clear).

+2


source







All Articles