Tuesday, 13 October 2015

Class Object and Class Name

The Class Object

Instances of the class Class represent classes and interfaces in a running Java application. An enum, annotation, every array, primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.

If we know the class name at compile time, we can obtain the name Class object:


Class myObjectClass = MyObject.class;


If you don't know the name at compile time, but have the class name as a string at runtime, you can do like this:


//obtain class name at runtime
String className = "core.MyClass";
// must supply the fully qualified class name
Class classObj = Class.forName(className);


The Class.forName() method may throw a ClassNotFoundException if the class cannot be found on the classpath at runtime.

Class has no public constructor. Instead Class objects are constructed automatically by the JVM as classes are loaded and by calls to the defineClass method in the class loader.

Class Name

Fully qualified class name (including package name) can be obtain using the getName() method.
Only class name (without pacakge name) can be obtain using the getSimpleName() method.


Class myObjectClass = MyObject.class;
String className = myObjectClass.getName(); // reflect.MyObject
String className = myObjectClass.getSimpleName();//MyObject

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...