java get class by name code example

Example 1: java class name to string

String className = n.getClass().getName();
String name = className.substring(className.lastIndexOf('$')+1,className.length()-4);
System.out.println(name);

Example 2: getting class name in java

a.getClass().getName();

Example 3: java get class by string

//get an according class variable
String className = "MyClass";
Class<?> cls = Class.forName(className);

//create instance of that class
Object myInstance = cls.newInstance();

Example 4: java get classname

//Just the name of the class
myObject.getClass().getSimpleName();

//The name of the class with the package name
myObject.getClass().getName();

Example 5: java get class name of object

myObject.getClass().getName()

Example 6: java get class by string name

//get an according class variable
String className = "MyClass";
Class<?> cls = Class.forName(className);

//create instance of that class
Object myInstance = scl.newInstance();

Tags:

Java Example