getClass() in abstract class gives Ambiguous method call

后端 未结 5 1567
北海茫月
北海茫月 2021-01-31 13:39

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:

相关标签:
5条回答
  • 2021-01-31 14:00

    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.

    0 讨论(0)
  • 2021-01-31 14:06

    I noticed that it depends on the Android version you are referencing whether the error occurs or not. I used to define a dependency for Android 4.1.1.4 in the pom.xml linking to Maven Central.

    <dependency>
        <groupId>com.google.android</groupId>
        <artifactId>android</artifactId>
        <version>4.1.1.4</version>
        <scope>provided</scope>
    </dependency>
    

    Meanwhile, I provide the needed dependencies using maven-android-sdk-deployer.

    <dependency>
        <groupId>android</groupId>
        <artifactId>android</artifactId>
        <version>4.3_r1</version>
        <scope>provided</scope>
    </dependency>
    

    Then getClass() produces the error.

    0 讨论(0)
  • 2021-01-31 14:09

    This can happen if you have an Android project with Maven, and you import into IntelliJ using the Maven Android Platform as the project SDK. The problem is that both Maven Android Platform and the Android maven dependency jar includes the java.lang.Object class.

    The workaround is goint to Project structure -> Platform Settings -> SDK -> Maven Android Platform -> Classpath. It will list all the jars which are in JDK actually. Remove all of them, so only the two Android dependency remains (res and annotations.jar).

    EDIT: This problem has been already reported to IntelliJ issue tracker long time ago.

    0 讨论(0)
  • 2021-01-31 14:20

    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.

    0 讨论(0)
  • 2021-01-31 14:25

    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();
    }
    
    0 讨论(0)
提交回复
热议问题