栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在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;    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/407148.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号