Java error: Found interface ... but class was expected

Viewed 33642

I am getting a strange runtime error from my code:

"Found interface [SomeInterface] but class was expected"

How can this happen? How can an interface get instantiated?

Update: (In response to some answers) I am compiling and running against the same set of libraries, but I am using Guice to inject a Provider for this particular Interface.

The problem went away when I bound an implementation to the interface (seems like the @ImplementedBy annotation was not enough).

I was more interested in the mechanics through which Guice managed to actually instantiate an interface.

5 Answers

This happens when your runtime classpath is different than your compile time classpath.

When your application was compiled, a class (named SomeInterface in your question) existed as a class.

When your application is running at compile time, SomeInterface exists as an interface (instead of a class.)

This causes an IncompatibleClassChangeError to be thrown at runtime.

This is a common occurence if you had a different version of a jar file on the compile time classpath than on the runtime classpath.

Most likely the code was compiled against a class in a library, which was then changed to an interface in the version you run against.

This happened to me when i was running a maven build.

From what i could gather (as well as from Jared's answer) as the reason was that - there were two versions of the same 3rd party jar specified in my effective pom.xml. One version was coming in as a transitive dependency and the other was specified by me in my local pom.xml.

So at compile time, it was referring to the old version and at runtime it was referring to the new version.

I removed the version specified in my local pom.xml and it worked.

Of course, the 3rd party had broken backward-compatibility between their versions and changed a class to an interface or vice-versa. But they are free to do so.

It sounds like you did

class MyClass extends SomeInterface

when it should actually be

class MyClass implements SomeInterface

Am I right?

EDIT: Oh, you say it's a runtime error and not a compile-time error? Let me look around a bit...

EDIT 2: It looks like Jared has the correct answer. Anyway, trying to extend an interface would actually give a "no interface expected here" message at compile time, not a "found interface but class was expected" error.

Related