Java 在静态方法中从抽象类查找扩展程序
我有一套基础课, ei:Java 在静态方法中从抽象类查找扩展程序,java,reflection,static,extend,superclass,Java,Reflection,Static,Extend,Superclass,我有一套基础课, ei: 公共类项目{ } 我想添加功能以扩展具有可存储能力的基本类: 用于防止数据存储在对象中的新参数 从存储器加载对象的新静态方法 我创建了一个可存储的抽象类: public abstract class Storable{ private StorageRow str; public void setStorageRow(StorageRow row){ str = row; } public static ArrayLi
公共类项目{
}
我想添加功能以扩展具有可存储能力的基本类:
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;
}
}
主要问题是:现在我在静态方法getAll的超类中。如何获得子类?你不能。静态方法属于您声明它的类,而不是它的子类()。因此,如果您想知道从何处调用它,您需要将类作为参数传递给它
public static ArrayList<? extends Storable> getAll(Class<? extends Storable>)
publicstaticarraylist不太确定您想做什么,但简单的回答是您可能做不到。但是您可能可以添加一个Item.getAll()
方法,该方法使用了Storable.getItem()
。如果您希望加载方法的行为具有多态性,则不能将其设置为静态。在我看来,这是一种简单的方法,它肯定会工作。缺点是代码看起来很难看:Item.getAll(Item.class)使用stack的技巧对我不起作用,因为我在stack中看到的是超类,而不是子类。我添加了一个示例,说明如何使用stacktrace让类调用静态方法。最好的办法是创建一个静态的类getCallingClass()
方法,并在必要时使用它。我仍然认为第一种方法更好,因为它更简单,更易维护,更可读。。。
public static ArrayList<? extends Storable> getAll(Class<? extends Storable>)
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();
}
}
}