Get the name of the Pair class via an instance

By having an instance (an object) of Pair, we can find out the name of its class by calling the getClass() method, as well as Class.getName(), getSimpleName(), and getCanonicalName(), as shown in the following example:

Class<?> clazz = pair.getClass();

// modern.challenge.Pair
System.out.println("Name: " + clazz.getName());

// Pair
System.out.println("Simple name: " + clazz.getSimpleName());

// modern.challenge.Pair
System.out.println("Canonical name: " + clazz.getCanonicalName());
An anonymous class doesn't have simple and canonical names.

Notice that getSimpleName() returns the unqualified class name. Alternatively, we can obtain the class as follows:

Class<Pair> clazz = Pair.class;
Class<?> clazz = Class.forName("modern.challenge.Pair");
..................Content has been hidden....................

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