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

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

    I believe what you are trying to do is possible with a bit of generics magic. I had to solve the same problem just now and this is what I did:

    public class ListArrayUtils{
       @SuppressWarnings("unchecked") // It is checked. 
       public static  List filterByType(List aList, Class aClass){
          List ans = new ArrayList<>();
          for(E e: aList){
             if(aClass.isAssignableFrom(e.getClass())){
                ans.add((T)e);
             }
          }
          return ans;
       }       
    }
    

    And unit tests:

    public class ListArrayUtilsTest{
       interface IfA{/*nothing*/}
       interface IfB{/*nothing*/}
       class A implements IfA{/*nothing*/}
       class B implements IfB{/*nothing*/}
       class C extends A implements IfB{/*nothing*/}
    
       @Test
       public void testFilterByType(){
          List data = new ArrayList<>();
          A a = new A();
          B b = new B();
          C c = new C();
          data.add(a);
          data.add(b);
          data.add(c);
    
          List ans = ListArrayUtils.filterByType(data, IfB.class);
    
          assertEquals(2, ans.size());
          assertSame(b, ans.get(0));
          assertSame(c, ans.get(1));
       }
    }
    
        

    提交回复
    热议问题