14

What is the difference between Java's Class.getName() and Class.getCanonicalName()?

durron597
  • 31,968
  • 17
  • 99
  • 158
  • 1
    Also See http://stackoverflow.com/questions/15202997/what-is-the-difference-between-canonical-name-simple-name-and-class-name-in-jav – Anurag Sharma Dec 17 '13 at 09:56
  • @Anush funny, I didn't see that one when looking it up, which is only a month older than mine. Thanks – durron597 Dec 17 '13 at 14:23

1 Answers1

17

Consider the following program:

package org.test.stackoverflow;

public class CanonicalName {

  public static void main(String[] args) {
    CanonicalName cn = new CanonicalName();
    cn.printClassNames();
  }

  private Anonymous anony;
  private MyAnony myAnony;

  public CanonicalName() {
    anony = new Anonymous() {
      public void printInterface() {
        System.out.println("Anony Name: " + getClass().getName());
        System.out.println("Anony CanonicalName: " + getClass().getCanonicalName());
      }
    };
    myAnony = new MyAnony();
  }

  public void printClassNames() {
    System.out.println("CanonicalName, Name: " + getClass().getName());
    System.out.println("CanonicalName, CanonicalName: " + getClass().getCanonicalName());
    anony.printInterface();
    myAnony.printInterface();
  }

  private static interface Anonymous {
    public void printInterface();
  }

  private static class MyAnony implements Anonymous {
    public void printInterface() {
      System.out.println("MyAnony Name: " + getClass().getName());
      System.out.println("MyAnony CanonicalName: " + getClass().getCanonicalName());
    }
  }
}

Output:

CanonicalName, Name: org.test.stackoverflow.CanonicalName
CanonicalName, CanonicalName: org.test.stackoverflow.CanonicalName
Anony Name: org.test.stackoverflow.CanonicalName$1
Anony CanonicalName: null
MyAnony Name: org.test.stackoverflow.CanonicalName$MyAnony
MyAnony CanonicalName: org.test.stackoverflow.CanonicalName.MyAnony

So it seems that for base classes, they return the same thing. For inner classes, getName() uses the $ naming convention (i.e. what is used for .class files), and getCanonicalName() returns what you would use if you were trying to instantiate the class. You couldn't do that with a (little-a) anonymous class, so that's why getCanonicalName() returns null.

durron597
  • 31,968
  • 17
  • 99
  • 158
  • 1
    It's impossible to find answer to your own question in just seconds. Looks like deception. Times of the question and the answer are exactly the same. – Maciej Ziarko Apr 01 '14 at 12:50
  • 9
    @MaciejZiarko There's a checkbox at the bottom "answer your own question, Q&A style. I wanted to add my recent discovery to the knowledge base in SO, because I couldn't find it anywhere. – durron597 Apr 01 '14 at 13:16
  • For future reference, don't name the class after the very concept you're trying to explore/portray... – Andrew Aug 22 '17 at 16:31