java get class code example
Example 1: get method of a class which I only have string to
String className = "my.class.name";
Object classObj = null;
try {
classObj = Class.forName(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Method classMethod = null;
try {
classMethod = classObj.getClass().getMethod("method", param1.class, param2.class, ..);
} catch (SecurityException | NoSuchMethodException e) {
e.printStackTrace();
}
try {
classMethod.invoke(classObj, arg1, args2, ..);
} catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException) {
e.printStackTrace();
}
Example 2: getting class name in java
a.getClass().getName();
Example 3: java get classname
myObject.getClass().getSimpleName();
myObject.getClass().getName();
Example 4: java get class name of object
myObject.getClass().getName()
Example 5: java get class by string name
String className = "MyClass";
Class<?> cls = Class.forName(className);
Object myInstance = scl.newInstance();