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

编辑

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

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 回答