我有一个类,它有一些不是实现细节的类型参数,还有一些是。
如果不使用未经检查的强制转换,那么处理不应成为公共API一部分的类型参数的最佳方法是什么?
我有一个类是由一个生成器创建的,它选择了正确的助手。在我的例子中,helper知道如何在类似缓冲区的对象之间进行大容量读/写。
/**
* @param <T> a type parameter that end users of PublicClass cannot ignore.
* @param <X> has a specific relationship to T, but
* is an artifact of how PublicClass is implemented.
*/
public class PublicClass<T> {
// This constructor is called from a builder.
// The builder just returns
// new PublicClass<>(aHelper, someMutableState)
// <X> is inferred from the choice of parameters.
<X> PublicClass(
Helper<T, X> helper,
StatefulInternalObject<T, X> someMutableState) {
...
}
...
}
所以有一个公共类和一个公共构建器,还有一些包私有实现细节类。
<X>
但我的助手和有状态对象需要以依赖于
<X>
<T>
<X>
,因此使用未检查的强制转换涉及
<X>
会使PublicClass的实现变得脆弱。
我可以创建另一个包含两组类型参数的隐藏类,然后使我的公共API转发到该类:
public class PublicCLass<T> {
private final class TypedImpl<T, ?> typeSafeImplementation;
<X> PublicClass(
Helper<T, X> helper,
StatefulInternalObject<T, X> someMutableState) {
typeSafeImplementation = new TypedImpl<>(
helper, someMutableState);
}
// Public API just forwards to an internal
// implementation class.
public SomeType0 someMethod(SomeType1 x) {
return typeSafeImplementation(x);
}
...
}