Java - 来自静态初始化 block 内部的类类型

标签 java reflection static-initializer static-initialization

是否可以从静态初始化 block 中获取类类型?

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

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);
   }
}

编辑

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

最佳答案

不,不抓取堆栈跟踪是不可能的(我觉得这比你最初的方法更糟糕,而且我更喜欢 new Exception() 之上的 Thread#getStackTrace())。

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

public abstract class SuperClass {

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

}

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

关于Java - 来自静态初始化 block 内部的类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2944972/

相关文章:

Java:验证类是否存在

java - Java中的同步概念不起作用?

java - 为什么对父构造函数的调用不是编译器为内部类生成的构造函数中的第一个调用?

java - 未处理的异常 : NoSuchMethodException

具有(和不具有)混合静态构造函数的 C# 静态初始化器

java - Twitter4j:显示特定用户帐户上带有搜索词的所有推文

java - 使用 JUnit 测试 protected 方法

java - 当来自其他包的类时方法调用失败

Java枚举反向查找最佳实践

C++0x 静态初始化和线程安全