How can I pass a Class as parameter and return a generic collection in Java?

后端 未结 7 1105
悲哀的现实
悲哀的现实 2020-12-24 05:18

I am designing a simple Data Access Object for my Java application. I have a few classes (records) that represents a single row in tables like User and Fr

相关标签:
7条回答
  • 2020-12-24 06:13

    You are pretty close.

    public <T> LinkedList<T> getAllRecords(List<T> list) {
     ...
    }
    

    This is called a Generic Method.

    You will want to specify a parameter like List<T>. Then, based upon the type of the list you pass in, Java will infer the generic type to return.

    Edit:

    Poly's answer is very good. It should be easy enough for you to do the following and not have to create a TypeReference class.

    List<Fruit> fruit = myDataAccessObject.getAllRecrods(new LinkedList<Fruit>());
    List<User> users = myDataAccessObject.getAllRecords(new LinkedList<User>());
    
    0 讨论(0)
提交回复
热议问题