【发布时间】:2012-02-01 07:49:59
【问题描述】:
我是 Java 新手,如果我完全搞错了,敬请见谅。
我正在尝试编写一个通用的(在英语意义上!)数据访问类。 例如,我目前有:
public class DA<T> {
public static Dao getAccountDao() throws NamingException, SQLException {
Context ctx = new InitialContext();
DataSource dataSource = (DataSource)ctx.lookup("java:comp/env/jdbc/test");
ConnectionSource connectionSource = new DataSourceConnectionSource(dataSource, new MysqlDatabaseType());
Dao<Account, Integer> accountDao = DaoManager.createDao(connectionSource, Account.class);
return accountDao;
}
}
我可以这样称呼它:
Dao<Account, Integer> accountDao = DA.getAccountDao();
但我需要为每个 Dao/模型提供一个版本。所以我正在尝试制作一些可以称为:
Dao<SomeClass, Integer> someClassDao = DA.getDao(SomeClass);
这可能吗?
我尝试过类似的方法:
public class DA {
public static Dao getDao(<T>) throws NamingException, SQLException {
Context ctx = new InitialContext();
DataSource dataSource = (DataSource)ctx.lookup("java:comp/env/jdbc/test");
ConnectionSource connectionSource = new DataSourceConnectionSource(dataSource, new MysqlDatabaseType());
Dao<T, Integer> accountDao = DaoManager.createDao(connectionSource, T.class);
return accountDao;
}
}
但 Netbeans 给出错误:illegal start of type
我的大脑正在与泛型作斗争,这是他们能做到的吗?!
编辑:在下面帖子的帮助下,我必须:
public class DA<T> {
public static Dao<T, Integer> getDao(T daoType) throws NamingException, SQLException {
Dao<T, Integer> accountDao = DaoManager.createDao(T.class);
return accountDao;
}
}
这会产生两个错误:
non-static type variable T cannot be referenced from a static context
如果我删除 static 关键字,我会得到:
cannot select from a type variable
我需要阅读泛型和静态如何协同工作,但第二个看起来像是擦除的结果(http://www.coderanch.com/t/386358/java/java/Converting-type-parameters-class),所以不确定是否可行。
前面应该提到,Dao 的东西使用了一个叫做 ORMLite 的 ORM 库,所以 createDao 等不是我的代码。
【问题讨论】:
-
我需要实现与您类似的目的,并且与您走相同的路线。但是您正在使用的 ORMLite 库提出了一种不同的解决方法。此评论不能回答您的问题,但可能会帮助您以更好的方式实现整体目标。请参阅此SO question for more details。希望对您有所帮助。