English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The only possible solution is to obtain the stack trace of the current thread. Use the elements in the stack trace to get the class name. Pass it to the forName() method of the Class class named Class.
This will return a Class object, which you can usenewInstance()method to get an instance of this class.
public class MyClass { String name = "Krishna"; private int age = 25; public MyClass() { System.out.println("Object of the class MyClass"); System.out.println("name: ",+this.name); System.out.println("age: ",+this.age); } public static void demoMethod() throws Exception { StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); StackTraceElement current = stackTrace[1]; Class.forName(current.getClassName()).newInstance(); } public static void main(String args[]) throws Exception { demoMethod(); } }
Output Result
Object of the class MyClass name: Krishna age: 25