Paul de Lange
Paul de Lange

Reputation: 10633

returning cast subclass

I have a superclass Entity and there are subclasses like Post, Comment etc.

I want to add to Entity a generic method that will return a cast list in the subclasses. So for example I want to call this:

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

I have tried this:

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

But I think the syntax is not what I am after because when I do this:

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

}

It gives the error Type mismatch.

Upvotes: 0

Views: 78

Answers (2)

svz
svz

Reputation: 4588

In case you want a generic method and not a generic class, you may try something like:

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

        //populate your list  

        return list;
    }
}

You can use it like this:
List<Post> list = Entity.findAll(Post.class);

Upvotes: 1

user180100
user180100

Reputation:

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

and

public class Post extends Entity<Post> {

Upvotes: 3

Related Questions