Getting the name of a certain type

Starting with JDK 8, we can get an informative string for the name of a certain type.

This method returns the same string as one or more of getName(), getSimpleName(), or getCanonicalName():

  • For primitives, it returns the same for all three methods:
System.out.println("Type: " + int.class.getTypeName()); // int
  • For Pair, it returns the same thing as getName() and getCanonicalName():
// modern.challenge.Pair
System.out.println("Type name: " + clazz.getTypeName());
  • For inner classes (like Entry is for Pair), it returns the same thing as getName():
// modern.challenge.Pair$Entry
System.out.println("Type name: "
+ Pair.Entry.class.getTypeName());
  • For an anonymous class, it returns the same thing as getName():
Thread thread = new Thread() {
public void run() {
System.out.println("Child Thread");
}
};

// modern.challenge.Main$1
System.out.println("Anonymous class type name: "
+ thread.getClass().getTypeName());
  • For arrays, it returns the same thing as getCanonicalName():
Pair[] pairs = new Pair[10];
// modern.challenge.Pair[]
System.out.println("Array type name: "
+ pairs.getClass().getTypeName());

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset