Java - 静态初始化块内部的类类型

Chr*_*row 5 java reflection static-initializer static-initialization

是否可以从静态初始化块内部获取类类型?

这是我目前拥有的简化版本::

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"
   }
}
Run Code Online (Sandbox Code Playgroud)

这更接近我正在做的事情,即初始化一个保存有关对象及其注释等信息的数据结构......也许我使用了错误的模式?

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);
   }
}
Run Code Online (Sandbox Code Playgroud)

编辑

我根据最适合我的问题的答案选择了接受的答案,但是在我看来,当前的所有三个答案都有其优点。

Bal*_*usC 1

不,如果不获取堆栈跟踪,这是不可能的(在我看来,这比您最初的方法更糟糕,并且我无论如何都更喜欢Thread#getStackTrace()上面的方法new Exception())。

而是在检查状态的抽象类的非静态初始化程序(或默认构造函数)中完成这项工作initialized

public abstract class SuperClass {

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

}
Run Code Online (Sandbox Code Playgroud)

依次调用的方法就可以安全了static