Hiago_RaD
Hiago_RaD

Reputation: 41

Is there any way to make a method from an interface return a generic List<> using the DAO pattern?

I am working with the DAO pattern on Java, and I will use it to basically initialize and return lists of objects. So I want to make a method that, when overridden, returns a list of objects of any type that the class which implements the interface chooses.

Now the method "getAllItens()" returns a list of "Item" objects, and I don't want to create another interface just to initialize different types of objects.

public interface Dao
{
    //...
    public List<Item> getAllItens();
    //...
}

Upvotes: 0

Views: 213

Answers (2)

Antoniossss
Antoniossss

Reputation: 32517

Yes, use generics for that

public interface Dao<T>
{
    //...
    List<T> getAllItems();
    //...
}

and

class YourConcreteDao implements Dao<Person>

Upvotes: 2

Jasper Huzen
Jasper Huzen

Reputation: 1573

If your are using Spring/Spring-boot you can also use Spring Data Repositories for your DAO layer. That gives you a lot of functionality for free (like this kind of methods).

Upvotes: -1

Related Questions