getClass() in abstract class gives Ambiguous method call
I have a public abstract class and I'm trying to use the getClass()
method, as I will need info from the class extending my abstract class. An example is this:
public String getName() {
return getClass().getSimpleName();
}
However, IntelliJ reports this:
Ambiguous method call. Both
getClass () in Object and
getClass () in Object match.
The code runs fine, but having tens of error warnings in my IDE is kinda in my way. It disrupts my work flow with a lot of false positives.
Why are these errors shown, and what can I do to not see them?
Solution 1:
Casting my getClass()
call to Object
like this
((Object) this).getClass()
solves the problem (with non abstract classes) for me. It's not great, but it's working.
Also, manipulating your Android SDKs from the project settings and removing all JDK jars from your Android SDK resolves the error. Of course you'll have to reference it within your project to utilize the fix.
Solution 2:
The code is fine, but it is an error in IntelliJ.
Error report, another one.
There are even some more error reports with different variations of this issue. As duffymo pointed out in comments, it can also be because there are different versions of the JDK in the classpath.
Solution 3:
Another working workaround is to generate a helper method to get the Class:
public Class<?> type() {
return super.getClass();
}
or a static reusable util:
public static final Class<?> type(Object object) {
return object.getClass();
}