我正在尝试创建一个基于具有基于泛型的集合的类的泛型服务
public class GenericClass<T> {
List<T> results;
public List<T> getResults() {
return results;
}
}我只是不确定如何创建一个基于此GenericClass并具有T的具体实现的服务。
public class ServiceManagerImpl<GenericClass<T>> implements ServiceManager<GenericClass<T>> {
public GenericClass<T> getMyClass() {
...
}
}但是编译器不喜欢这样。你知道该怎么做吗?
Marc
发布于 2012-07-09 13:11:24
你已经接近了..。只需传递T:
public class ServiceManagerImpl<T> implements ServiceManager<GenericClass<T>> {
public GenericClass<T> getMyClass() {
...
}
}发布于 2012-07-09 12:29:55
<>之间的内容称为,并且GenericClass<T>在声明中不是有效的类型参数。
引用自java generic guide
泛型类的定义格式如下:
类name { /* ... */ }
类型参数部分位于类名之后,由尖括号(<>)分隔。它指定类型参数(也称为类型变量) T1、T2、...和Tn。
因此,您需要在实现中使用GenericClass<T>,而不是在声明中。
// declaration
public class ServiceManagerImpl<YourGenericType> implements ServiceManager<YourGenericType> {
public YourGenericType getMyClass() {
...
}
}
// implementation
ServiceManager<GenericClass<Object>> sm = new ServiceManagerImpl<GenericClass<Object>>();发布于 2012-07-09 12:37:03
public class ServiceManagerImpl<T extends GenericClass<T>> implements ServiceManager<T extends GenericClass<T>> {
public GenericClass<T> getMyClass() {
...
}
}https://stackoverflow.com/questions/11385220
复制相似问题