是否可以从静态初始化 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/