如何在不使用Java静态上下文的情况下使用类名的情况下访问类的对象?
唯一可能的解决方案是获取当前线程的堆栈跟踪。使用堆栈跟踪中的元素获取类名称。将其传递给名为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
热门推荐
10 乔迁仪式文案祝福语简短
11 身体康复的祝福语简短
12 朋友家住豪宅祝福语简短
13 给长辈祝福语简短大全
14 18岁祝福语搞笑简短
15 祝福语诗意文案简短
16 整形机构开业祝福语简短
17 年前幸福祝福语大全简短
18 新娘上头祝福语大全简短