What's the difference between Name and CanonicalName? [duplicate]
Asked Answered
R

1

14

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

Reptant answered 9/4, 2013 at 13:46 Comment(2)
Also See #15203497Strigose
@Anush funny, I didn't see that one when looking it up, which is only a month older than mine. ThanksReptant
R
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.

Reptant answered 9/4, 2013 at 13:46 Comment(3)
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.Ranket
@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.Reptant
For future reference, don't name the class after the very concept you're trying to explore/portray...Effluvium

© 2022 - 2024 — McMap. All rights reserved.