Android Studio - Ambiguous method call getClass()

Solution 1:

I think it is a bug in Android Studio. As we know, Android Studio is based on the IntelliJ Platform and the existing functionality of IntelliJ IDEA Community Edition.

Google has developed it in cooperation with JetBrains. And same bug is reported to happen in IntelliJ as well. Have a look at the Error report

The only workaround to this issue is to cast the instance you call getClass() on, to Object as follows:

((Object) this).getClass()

Solution 2:

Rather than modify your application code, you can avoid this bug by patching your Android SDK's source code.

When you come across the getClass() error, go to the declaration of the method (⌘B on Mac). This will navigate to a path such as $ANDROID_HOME/sources/android-20/java/lang/Object.java. Now, within IntelliJ or Android Studio:

  • Make Object.java writable by choosing File -> Make File Writable. You may be prompted to do this automatically if you try to edit the file.
  • Remove the unbounded wildcard:

    // Removed unbounded wildcard (Class) to avoid http://youtrack.jetbrains.com/issue/IDEA-72835 public final native Class getClass();

Newer versions of Android Studio appear to suffer from a bug which prevents you from editing the file even after declaring it as writable. Instead, copy the path, Edit -> Copy Path or ⇧⌘C, and edit it in your favorite editor.

This change will preserve source navigation functionality. Other options:

  • You may comment out the entire getClass() declaration.
  • You may append a non-Java extension to the name of the Object.java file, e.g. Object.java.in.