2012-12-20 19 views
0

我有一個超Entity和有子像PostComment歸國投子

我想要添加到Entity,將返回在子類中一個演員表的通用方法。因此,例如,我想稱之爲:

List<Post> posts = Post.findAll(); 

我已經試過這樣:

public class Entity { 
    public static List<?> findAll() { 
     return ???; 
    } 
} 

但是我覺得語法是不是我什麼,因爲後,當我這樣做:

for(Post post : Post.findAll()) { 

} 

它給出了錯誤Type mismatch

回答

1

如果你想有一個通用的方法,而不是一個泛型類,你可以嘗試類似:

public class Entity { 
    static <T extends Entity> List<T> findAll(Class<T> type){ 
     List<T> list = new ArrayList<T>(); 

     //populate your list 

     return list; 
    } 
} 

您可以使用它像這樣:
List<Post> list = Entity.findAll(Post.class);

+0

可能最接近我可以得到我想要的 –

+0

@Paul,很高興幫助。如果它適合您,您可以考慮將其標記爲答案。 – svz

3
public class Entity<T> { 
    public List<T> findAll() { 
     return ???; 
    } 
} 

public class Post extends Entity<Post> { 
+0

無法對l中的非靜態類型進行靜態引用ine:public static List findAll() –

+0

已更正的代碼。 – 2012-12-20 13:17:30

+0

好的,但它不再是靜態的。我猜你不能這樣做在java –