我想改善我的代码,特别是我使用泛型类的方式。
在我的项目中,我有大约30课,例如:
GenericEntity<T extends Serializable>{
protected T id;
public T getId(){ return id;};
...
}
public class A extends GenericEntity<Integer>{
...
}
public interface IService<T extends GenericEntity, T extends Serializable>{
...
}
public class AService extends IService<A,Integer>{
...
}
我只想一次指定我的实体ID的类,而不是在GenericEntity中指定一次,而在Service中这样指定一次。
public class A extends GenericEntity<getIdType()>{
public final static Class getIdType(){
return Integer.class;
}
}
public class AService extends IService<A,A.getIdType()>{
...
}
我知道它不能那样工作,但我希望有一种方法可以做到。
谢谢你的帮助。
最佳答案
代替:
class GenericEntity<T extends Serializable>{
protected T id;
public T getId(){ return id;};
}
// THESE ARE UNNECESSARY as far as I can tell
class A extends GenericEntity<Integer>{ }
class B extends GenericEntity<Long>{ }
// where U matches the generic type of GenericEntity<?>
interface IService<T extends GenericEntity<?>, U extends Serializable>{ }
class AService extends IService<A, Integer>{ }
class BService extends IService<B, Long>{ }
您可以这样做:
class GenericEntity<T extends Serializable> {
protected T id;
public T getIdFromEntity() { return id; }
}
// 'IService' can/should only know of 'id' as some type that extends 'Serializeable'
// So if something implements 'IService' then everything knows it will have
// a method with the signature 'T getGenericEntity(Serializable id);'
interface IService<T extends GenericEntity<?>> {
public T getGenericEntity(Serializable id);
}
// 'AService' knows that 'id' will be an 'Integer'
class AService implements IService<GenericEntity<Integer>> {
Map<Serializable, GenericEntity<Integer>> entityMap = new HashMap<>();
void someMethod() {
GenericEntity<Integer> entity = this.getGenericEntity(Integer.valueOf(1));
Integer i1 = entity.getIdFromEntity();
// ... do stuff
}
// even though 'AService' knows that 'id' will be an 'Integer'
// the 'IService' interface defines this as taking a 'Serializable'
// so it must keep that method signature.
@Override public GenericEntity<Integer> getGenericEntity(Serializable id) {
return entityMap.get(id);
}
}
class BService implements IService<GenericEntity<Long>> {
@Override public GenericEntity<Long> getGenericEntity(Serializable id) { return null; }
// ... similar to AService ...
}
这将消除所有多余的
class X extends GenericEntity<SOME_TYPE>
类。您只需要一个通用的
GenericEntity<T extends Serializable>
和一个interface IService<T extends GenericEntity<?>>
。另外,由于它们不是通用的AService
,而BService
知道扩展Serializeable
的实际类型(整数和长整数),因此它们不需要传递给泛型的额外信息。由于
IService
对于任何T extends GenericEntity<?>
是通用的,因此它不应该知道genericEntity.getId()
的具体类型(并且您可能不希望这样做)。另外,您应该避免使其具体化,因为它是Interface
。就
id
而言,IService
的类型为Serializable
,因为IService<GenericEntity<?>>
表示通配符?
扩展了Serializeable
,因为class GenericEntity<T extends Serializeable>
要求通配符。