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

后端 未结 7 1109
悲哀的现实
悲哀的现实 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 05:47

    Well, I really don't know if you need it this way. But here is a polymorphic approach. It might help somewhere somehow.

    Create different objects for different tables all implementing a common interface. This means you represent each table as an object.

    import java.util.LinkedList;
    
    public class DataAccessTest 
    {
    
        /**
         * @param args
         */
        public static void main(String[] args) 
        {
            DataAccess myDataAccessObject = new DataAccess();
            Type type1 = new Fruit();
            Type type2 = new User();
            LinkedList list1 = myDataAccessObject.getAllRecords(type1);
            LinkedList list2 = myDataAccessObject.getAllRecords(type2);
            LinkedList list3 = myDataAccessObject.getAllRecords(new Fruit());
            LinkedList list4 = myDataAccessObject.getAllRecords(new User());
        }
    }
    
    class DataAccess
    {
        public LinkedList getAllRecords(Type type)
        {
            return type.getAllRecords();
        }
    }
    
    interface Type
    {
        public LinkedList getAllRecords();
    }
    
    class Fruit implements Type
    {
        public LinkedList getAllRecords()
        {
            LinkedList list = new LinkedList();
            list.add(new Fruit());
            return list;
        }
    }
    
    class User implements Type
    {
        public LinkedList getAllRecords() 
        {
            LinkedList list = new LinkedList();
            list.add(new User());
            return list;
        }
    }
    

提交回复
热议问题