How can I pass a Class as parameter and return a generic collection in Java? -
I am preparing a simple data access object for my Java application. I have a few squares (records) that represent a line in tables like user
and fruit
.
Let me have a single method
For this time I like this: GetAllUsers () {...} public list & lt; Fruit & gt;
But I have to do a single polymorphous method like this:
Public list & lt; T & gt; GetAllRecords (class type) {if (user type example) {// select JDBC and SQL * from user) Otherwise (example of forest type) {// Use JDBC and SQL * Frames} use the return archive; }
Example for use:
list & gt; Fruit & gt; Fruit = myDataAccessObject.getAllRecrods (fruit class); & Lt; Users & gt; User = myDataAccessObject.getAllRecords (User.class);
How can I do this in Java?
You say that you do not want you to have data access methods in different classes (Anish's answer In the comment), I thought why not try to do this.
Public Class Records {Public Interface Recorder & lt; T & gt; {Public listing & lt; T & gt; GetRecords (); } Fixed recordphrase & lt; Fruit & gt; Fruit = new recordeter & lt; Fruit & gt; () {Public listing & gt; Fruit & gt; GetRecords () {...}}; Fixed recordphrase & lt; Users & gt; User = new recordeter & lt; Users & gt; () {Public listing & lt; Users & gt; GetRecords () {...}}; Public static zero main (string [] args) {list & lt; Fruit & gt; FruitRecords = Records.Fruit.getRecords (); & Lt; Users & gt; UserRecords = Records.User.getRecords (); }}
Edit:
I would like to add another one of my implementations.
public class test {public static zero main (string [] args) {test data entry = new test (); & Lt; Fruit & gt; FruitList = DataAccess.getAllRecords (Fruit.myType); & Lt; Users & gt; UserList = dataAccess.getAllRecords (User.myType); } & Lt; T & gt; & Lt; T & gt; GetAllRecords {T-CL} {List & lt; T & gt; List = New Arrestist & lt; T & gt; (); If (CAC crop) {// select JDBC and SQL * Use frames] and if (CL Instance of user) {// Select JDBC and SQL * urls) URL return list; }} Class fruit {fixed end result myType; Stable {myType = new fruit ();}} class user {fixed end user myType; Static {myType = new user}}}
edit :
I think the implementation is the same as you did Have asked
test of public class {public static zero main (string [] args throws InstantiationException, IllegalAccessException {test data entry = new test (); & Lt; Fruit & gt; FruitList = DataAccess.getAllRecords (Fruit.class); & Lt; Users & gt; UserList = dataAccess.getAllRecords (User.class); } & Lt; T & gt; & Lt; T & gt; GetAllRecords throws InstantiationException (class & lt; T & gt; CL); IllegalAccessException {t inst = cl.newInstance (); & Lt; T & gt; List = New Arrestist & lt; T & gt; (); If (for example fruit) {// Use JDBC and SQL * Select from the user] and if (for user example) {// select JDBC and SQL * from) Return of the fruit list; }}
Comments
Post a Comment