English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
현재 스레드의 스택 트래킹을 얻는 것은 유일한 가능한 해결책입니다. 스택 트래킹 요소를 사용하여 클래스 이름을 얻습니다. 이를 Class 클래스의 forName() 메서드에 전달합니다.
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
Class of the MyClass name: Krishna age: 25