在Java中为方法级泛型添加边界
我正在从事DTO和域对象之间映射的工作或项目。作为映射过程的一部分,我有以下接口:
public interface DomainObjectLookup {
<T> T lookup(final Class<T> type, final Long id);
}
在Mapper类中,我们使用查找
private final DomainObjectLookup lookup;
public Employer fromDto(EmployerNoNameDto dto) {
final com.bizo.dtonator.domain.Employer o;
if (dto.id != null) {
o = lookup.lookup(com.bizo.dtonator.domain.Employer.class, dto.id);
}
}
我遇到的问题是,我想在实现DomainObjectLookup的类中为泛型类型添加额外的限制。如果我有一个像
public interface HasId {
public Long getId();
public void setId(Long id);
}
以及DomainObjectLookup的子类
final class StubDomainLookup implements DomainObjectLookup {
private final Map<String, Object> objects = new HashMap<String, Object>();
public void store(final Long id, final Object instance) {
objects.put(key(instance.getClass(), id), instance);
}
@Override
public <T> T lookup(Class<T> type, Long id) {
final T instance = (T) objects.get(key(type, id));
if (instance == null) {
throw new IllegalStateException("Instance not found " + type + "#" + id);
}
return instance;
}
private static String key(final Class<?> type, final Long id) {
return type + "#" + id;
}
}
如何指定'T'必须实现'HasId'
共 (0) 个答案