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

时间:2010-05-31 17:06:31

标签: 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"
   }
}

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

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 个答案:

答案 0 :(得分:1)

是的,我经常使用它来初始化一个静态Log变量:

e.g。 :

public class Project implements Serializable, Cloneable, Comparable<Project> {
    private static final Logger LOG = LoggerFactory.getLogger(Project.class);
    ...

答案 1 :(得分: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作为参数。

答案 2 :(得分:1)

不,没有抓住堆栈跟踪是不可能的(这比你最初的方法更糟糕,我更倾向于Thread#getStackTrace()以上new Exception()。)

而是在检查initialized状态的抽象类的非静态初始化程序(或默认构造函数)中执行该作业。

public abstract class SuperClass {

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

}

被调用的方法可以安全地static