title: How can I pass a Class as parameter and return a generic collection in Java?
body: <p>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 <code>User</code> and <code>Fruit</code>.</p>
  
  <p>I would like to have a single method for getting all records of a specific type.</p>
  
  <p>For the moment I have it like this:</p>
  
  <pre><code>public List&lt;User&gt; getAllUsers() {
   ...
  }
  
  public List&lt;Fruit&gt; getAllFruits() {
   ...
  }
  
  ....
  </code></pre>
  
  <p>But I would like to have a single polymorphic method like this (wrong):</p>
  
  <pre><code>public List&lt;T&gt; getAllRecords(Class&lt;T&gt; type) {
      if(type instanceof User) {
          // Use JDBC and SQL SELECT * FROM user
      } else if(type instanceof Fruit) {
          // Use JDBC and SQL SELECT * FROM fruit
      }
      return collection;
  }
  </code></pre>
  
  <p>Example for uses:</p>
  
  <pre><code>List&lt;Fruit&gt; fruits = myDataAccessObject.getAllRecrods(Fruit.class);
  List&lt;User&gt; users = myDataAccessObject.getAllRecords(User.class);
  </code></pre>
  
  <p>How can I do this in Java?</p>