我想改进我的代码,特别是我使用通用类的方式。 在我的项目中,我有大约 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>
要求它。
关于Java 使用 const 或 static 方法定义通用类参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47675431/