我有一套基本课程, EI:
public class Item{
}
我想添加功能以扩展具有可存储能力的基本类:
我创建了一个抽象类Storable:
public abstract class Storable{
private StorageRow str;
public void setStorageRow(StorageRow row){
str = row;
}
public static ArrayList<? extends Storable> getAll(){
ArrayList<Storable> ans = new ArrayList<Storable>();
Class<Storable> extenderClass = ??????
ArrayList<StorageRow> rows = Storage.get(llallala);
for(StorageRow row : rows){
Object extender = extenderClass.newInstance();
// Now with reflection call to setStorageRow(row);
}
return ans;
}
}
现在我用Storable扩展我的基础课程:
public class Item extends Storable{}
电话是:
ArrayList<Item> items = (ArrayList<Item>) Item.getAll();
主要问题是:现在我在超类的静态方法getAll中。如何获得子类?
答案 0 :(得分:2)
你做不到。静态方法属于您声明它的类,而不属于其子类(they're not inherited)。因此,如果您想知道调用它的位置,则需要将类作为参数传递给它。
public static ArrayList<? extends Storable> getAll(Class<? extends Storable>)
另一个更麻烦的方法是获取堆栈跟踪并检查哪个类执行了调用,但是当参数足够时,我不认为这种黑客是值得的。
编辑:使用stacktrace的示例:
class AnotherClass {
public AnotherClass() {
Main.oneStaticMethod();
}
}
public class Main {
/**
* @param args
* @throws OperationNotSupportedException
*/
public static void main(final String[] args) {
new AnotherClass();
}
public static void oneStaticMethod() {
final StackTraceElement[] trace = Thread.currentThread()
.getStackTrace();
final String callingClassName = trace[2].getClassName();
try {
final Class<?> callingClass = Class.forName(callingClassName);
System.out.println(callingClass.getCanonicalName());
} catch (final ClassNotFoundException e) {
e.printStackTrace();
}
}
}