2

我有一组基本类,ei:

public class Item{ }

我想添加功能以扩展具有 Storable 能力的基本类:

  1. 用于防止数据存储在对象中的新参数
  2. 从存储中加载对象的新静态方法

我创建了一个抽象类 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 中。如何获得子类?

4

1 回答 1

2

你不能。静态方法属于您声明它的类,而不是它的子类(它们不是继承的)。因此,如果您想知道它是从哪里调用的,则需要将类作为参数传递给它。

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();
        }
    }
}
于 2013-04-12T18:10:21.727 回答