如何在Java中传递Class作为参数并返回通用集合?

如何在Java中传递Class作为参数并返回通用集合?,第1张

如何在Java中传递Class作为参数并返回通用集合

既然您说不想在不同的类中使用数据访问方法(在Anish的回答中),所以我想为什么不尝试这样的方法。

public class Records {    public interface RecordFetcher<T>{        public List<T> getRecords();    }    static RecordFetcher<Fruit> Fruit=new RecordFetcher<Fruit>(){        public List<Fruit> getRecords() { ...        }    };    static RecordFetcher<User> User=new RecordFetcher<User>(){        public List<User> getRecords() { ...        }       };    public static void main(String[] args) {        List<Fruit> fruitRecords=Records.Fruit.getRecords();        List<User> userRecords=Records.User.getRecords();    }}

编辑:

我想再添加一个实现。

public class Test {     public static void main(String[] args)     {        Test dataAccess=new Test();       List<Fruit> FruitList=dataAccess.getAllRecords(Fruit.myType);       List<User> UserList=dataAccess.getAllRecords(User.myType);    }     <T> List<T> getAllRecords(T cl)    {        List<T> list=new ArrayList<T>();        if(cl instanceof Fruit)        {  // Use JDBC and SQL SELECt * FROM fruit        }        else if(cl instanceof User)        { // Use JDBC and SQL SELECt * FROM user        }        return list;    }}class Fruit{    static final Fruit myType;    static {myType=new Fruit();}}class User{    static final User myType;    static {myType=new User();}}

编辑

我认为这种实现方式就是您所要求的

public class Test {     public static void main(String[] args) throws InstantiationException, IllegalAccessException     {        Test dataAccess=new Test();       List<Fruit> FruitList=dataAccess.getAllRecords(Fruit.class);       List<User> UserList=dataAccess.getAllRecords(User.class);    }     <T> List<T> getAllRecords(Class<T> cl) throws InstantiationException, IllegalAccessException    {        T inst=cl.newInstance();        List<T> list=new ArrayList<T>();        if(inst instanceof Fruit)        {  // Use JDBC and SQL SELECt * FROM user        }        else if(inst instanceof User)        { // Use JDBC and SQL SELECt * FROM fruit        }        return list;    }}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5016860.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-15
下一篇2022-11-15

发表评论

登录后才能评论

评论列表(0条)

    保存