我有一个带签名的方法:
public static <T, E extends PxViewFull<T> > E create(Class<T> dtoClass, Class<E> viewClass)
当我将其称为参数化第二个参数时,我会收到类型安全警告。调用方法:
private PxViewFull<Output40942DTO> output40813 = PxViewFull.create(Output40813DTO.class, ServiceOutputView.class);
ServiceOutputView签名:
public class ServiceOutputView<T extends ServiceCall<?>> extends PxViewFull<T>
如何推断泛型类型参数以消除警告?
答案 0 :(得分:0)
@Paul Bellora回答了你的问题。
ServiceOutputView.class类型为Class [ServiceOutputView [?]],并且您在调用站点的参数需要Class [ServiceOutputView [Output40942DTO]],因此当您尝试传递Class [ServiceView [?]时,您会得到一个未经检查的方法调用异常。 ]到类[ServiceOutputView [Output40942DTO]],这是你的方法类型参数告诉它的期望。
更新: 这是一种不会发出警告的安排:
public class Parameter {
public static void main(String... args) throws Exception {
PxViewFull<OutputDTO> output40813 = PxViewFull.create(OutputDTO.class, ServiceOutputView.class);
}
}
class ServiceCall<X> {
}
class OutputDTO extends ServiceCall<OutputDTO> {
public OutputDTO serviceCall() {
// i guess i pupulate myself?
return this;
}
}
class PxViewFull<X> {
private X dtoObject;
private Class<X> dtoObjectType;
public static <P1, P2 extends PxViewFull<?>, RESULT extends PxViewFull<P1>> RESULT create(
Class<P1> dtoClass,
Class<P2> viewClass) throws Exception {
return null;
}
public void setDtoObjectType(final Class<X> dtoObjectType) {
this.dtoObjectType = dtoObjectType;
}
public void setModel(Object o) {
if (!dtoObjectType.isInstance(o))
throw new IllegalArgumentException();
this.dtoObject = dtoObjectType.cast(o);
}
}
class ServiceOutputView<T extends ServiceCall<?>> extends PxViewFull<T> {
}
create方法必须包含一个未经检查的强制转换,最好的办法就是在它上面打一个@SuppressWarning,并确保在方法的javadoc中明确说明原因。