如何從靜態上下文中訪問類物件,而不透過類名訪問 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

更新於: 05-Aug-2019

620 個瀏覽

職業啟航

完成課程後獲得認證

開始
廣告