0

我有一个超类Entity,还有像Post等子类Comment

我想添加Entity一个通用方法,该方法将在子类中返回一个演员表。所以例如我想这样称呼:

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

我试过这个:

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

但我认为语法不是我所追求的,因为当我这样做时:

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

}

它给出了错误Type mismatch

4

2 回答 2

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

public class Post extends Entity<Post> {
于 2012-12-20T13:03:51.857 回答
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);

于 2012-12-20T13:42:18.043 回答