English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
L'unica soluzione possibile è ottenere il tracciamento della pila del thread corrente. Utilizzare gli elementi della pila del tracciamento per ottenere il nome della classe. Passarlo al metodo forName() della classe denominata Class.
这将返回一个Class对象,您可以使用newInstance()方法获取此类的实例。
public class MyClass { String name = "Krishna"; private int age = 25; public MyClass() { System.out.println("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(); } }
输出结果
MyClass类的对象 name: Krishna age: 25