English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

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
おすすめ