如何从静态上下文中访问类对象,而不通过类名访问 Java?
唯一可能的解决方案是获取当前线程的堆栈轨迹。使用堆栈轨迹中的某个元素获取类名。将其传递给名为 Class 的类的 forName() 方法。
这会返回一个类对象,可以使用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP