2013-04-12 68 views
2

我有一組基本類, EI:尋找從抽象類擴展的靜態方法

public class Item{ }

我想補充的功能擴展與耐儲藏能力基本類:

  1. 用於將數據從存儲器保存在對象中的新參數
  2. 從存儲器加載對象的新靜態方法

我創建了一個抽象類,可存儲:

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

現在,我向我的基本類可保存:

public class Item extends Storable{}

電話是:

ArrayList<Item> items = (ArrayList<Item>) Item.getAll(); 

主要問題是:現在我在超類的靜態方法getAll中。如何獲得一個子類?

+1

不太清楚你想要做什麼,但簡單的答案是,你可能做不到。但是你可以添加一個'Item.getAll()'方法,它使用'Storable.getItem()'。 –

+2

如果您希望您的加載方法呈多態行爲,則不能將其設爲靜態。 –

回答

2

你不能。靜態方法屬於您聲明它的類,而不屬於它的子項(they're not inherited)。所以如果你想知道它被調用的地方,你需要將類作爲參數傳遞給它。

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(); 
     } 
    } 
} 
+0

在我看來,這是簡單的方法,它肯定會奏效。 缺點是代碼看起來很難看:Item.getAll(Item.class) 堆棧的技巧並不適用於我,因爲我看到堆棧中的超類,而不是子類 – AndreyP

+0

我已經添加了一個關於如何使用堆棧跟蹤來獲得調用靜態方法的類。最好的辦法是創建一個靜態的'Class getCallingClass()'方法並在必要時使用它。我仍然認爲第一種方式更好,因爲它更簡單,更易於維護,更具可讀性...... – m0skit0