English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
الحل الوحيد المحتمل هو الحصول على سجل الدعوة الحالي للسطر. استخدم عناصر سجل الدعوة للحصول على اسم الصف. نقله إلى طريقة forName() للصف المسمى Class.
سيقوم هذا بتقديم Class object، يمكنك استخدامهnewInstance()للحصول على نموذج هذا الكائن.
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(); } }
نتيجة الخروج
Object of the class MyClass name: Krishna age: 25