是否可以获得通用参数的类?
我对泛型有点蹩脚,但我想知道,对于下面的类:
static class SomeClass<T> {
private T value;
public SomeClass(T value) {
T.class?
this.value = value;
}
public T getValue() {
return value;
}
}
如果调用例如: SomeClass
是否可以在构造函数中获取 String.class (或任何 T )?
好的,等一下,我要解释一下我要解决的问题
实际问题是我正在使用 OrmLite 和我有很多 DAO 对象,比如这个:
public class PostDAO extends BaseJdbcDao<Post, String> {
public PostDAO(DatabaseType databaseType) {
super(databaseType, Post.class);
}
}
对于 Domain
来说是:
public class DomainDAO extends BaseJdbcDao<Domain, String> {
public DomainDAO(DatabaseType databaseType) {
super(databaseType, Domain.class);
}
}
等等。我想对它们进行参数化,这样我就只能有一个:
public class DAO<K, V> extends BaseJdbcDao<K, V> {
public DAO(DatabaseType databaseType) {
super(databaseType, (WHAT HERE?));
}
}
但我陷入了这里是什么
部分)
I'm kind of lame with generics, but I wonder, for the following class:
static class SomeClass<T> {
private T value;
public SomeClass(T value) {
T.class?
this.value = value;
}
public T getValue() {
return value;
}
}
If called for example:SomeClass<String> stringer = new SomeClass<String>("Hello");
Is it possible to get String.class
(or whatever T would be) in the constructor?
Ok, wait a sec, I'm going to explain what I'm trying to solve
The actual problem is that I'm using OrmLite and I have a lot of DAO objects, like this one:
public class PostDAO extends BaseJdbcDao<Post, String> {
public PostDAO(DatabaseType databaseType) {
super(databaseType, Post.class);
}
}
For Domain
it is:
public class DomainDAO extends BaseJdbcDao<Domain, String> {
public DomainDAO(DatabaseType databaseType) {
super(databaseType, Domain.class);
}
}
and so on. I wanted to parametrize these, so that I can only have one:
public class DAO<K, V> extends BaseJdbcDao<K, V> {
public DAO(DatabaseType databaseType) {
super(databaseType, (WHAT HERE?));
}
}
but I'm stuck on the what here
part)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
value.getClass() 应该可以解决问题(假设 value 永远不为 null!)
value.getClass() should do the trick (assuming value is never null!)
怎么样:
What about:
@pakore 的答案是一个很好的答案,但我想补充一点,您没有来定义每类 DAO 对象。我在 ORMLite 文档中推荐了它,但它应该是一种方便,而不是一种痛苦。
您始终可以使用 BaseJdbcDao 作为匿名类执行类似以下操作:
我在 ORMLite junit 测试中经常这样做。拥有如下所示的实用方法可能会更好。我刚刚将其添加到将在 2.7 版本中发布的
BaseJdbcDao
类中。@pakore's answer is a good one but I wanted to add that you don't have to define the per-class DAO object. I recommended it in the ORMLite documentation but it's supposed to be a convenience, not a pain.
You can always do something like the following using
BaseJdbcDao
as an anonymous class:I do that a lot in the ORMLite junit tests. Might be better to have a utility method like the following. I've just added it to the
BaseJdbcDao
class which will be in the 2.7 release.