4

静的初期化ブロック内からクラス型を取得することは可能ですか?

これは私が現在持っているものの簡略化されたバージョンです::

class Person extends SuperClass {

   String firstName;

   static{
      // This function is on the "SuperClass":
      //  I'd for this function to be able to get "Person.class" without me
      //  having to explicitly type it in but "this.class" does not work in 
      //  a static context.
      doSomeReflectionStuff(Person.class);     // IN "SuperClass"
   }
}

これは、オブジェクトとその注釈などに関する情報を保持するデータ構造を初期化するという、私が行っていることに近いです...おそらく間違ったパターンを使用していますか?

public abstract SuperClass{
   static void doSomeReflectionStuff( Class<?> classType, List<FieldData> fieldDataList ){
      Field[] fields = classType.getDeclaredFields();
      for( Field field : fields ){
         // Initialize fieldDataList
      }
   }
}

public abstract class Person {

   @SomeAnnotation
   String firstName;

   // Holds information on each of the fields, I used a Map<String, FieldData>
   //  in my actual implementation to map strings to the field information, but that
   //  seemed a little wordy for this example
   static List<FieldData> fieldDataList = new List<FieldData>();

   static{
      // Again, it seems dangerous to have to type in the "Person.class"
      //   (or Address.class, PhoneNumber.class, etc...) every time.
      //   Ideally, I'd liken to eliminate all this code from the Sub class
      //   since now I have to copy and paste it into each Sub class.
      doSomeReflectionStuff(Person.class, fieldDataList);
   }
}

編集

私の問題に最もよく当てはまるものに基づいて受け入れられた回答を選択しましたが、現在の3つの回答すべてにメリットがあるようです。

4

3 に答える 3

1

はい、これを頻繁に使用して静的ログ変数を初期化します。

例:

public class Project implements Serializable, Cloneable, Comparable<Project> {
    private static final Logger LOG = LoggerFactory.getLogger(Project.class);
    ...
于 2010-05-31T17:13:00.270 に答える
1

実行時にクラスを取得するには、次の行に沿って何かを行うことができます

public class Test {
public static void main(String[] args) {
    try{
        throw new Exception();
    }
    catch(Exception e){
        StackTraceElement[] sTrace = e.getStackTrace();
        // sTrace[0] will be always there
        String className = sTrace[0].getClassName();
        System.out.println(className);

    }
}

}

きれいではありませんが、仕事をします(http://www.artima.com/forums/flat.jsp?forum=1&thread=155230から抜粋)。

これは、引き続きサブクラスから呼び出しを行うことを意味しますが (スタック トレースでもそうです)、引数として XXX.class を含める必要はありません。

于 2010-05-31T17:16:48.657 に答える
1

いいえ、スタックトレースを取得しないと不可能です(これは、最初のアプローチよりも厄介であり、何らかの方法でThread#getStackTrace()上記を好むでしょうnew Exception())。

initializedむしろ、ステータスをチェックする抽象クラスの非静的初期化子 (またはデフォルトのコンストラクター) でそのジョブを実行します。

public abstract class SuperClass {

    {
        if (!isInitialized(getClass())) {
            initialize(getClass());
        }
    }

}

呼び出されたメソッドは、安全に実行できますstatic

于 2010-05-31T17:19:33.900 に答える