如何在不使用 Java 静态上下文中的类名的情况下访问类的对象?
java 8object oriented programmingprogramming更新于 2025/9/21 1:48:17
唯一可能的解决方案是获取当前线程的堆栈跟踪。使用堆栈跟踪中的元素获取类名。将其传递给名为 Class 的类的 forName() 方法。
这将返回一个 Class 对象,您可以使用 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

