Java在层次化构建器模式中避免类转换警告 [英] Java avoid class cast warning in hierarchical Builder pattern
问题描述
public abstract class BaseBuilder< T 有没有办法避免在这个分层构造器模式中进行未经检查的类的强制转换? ,B扩展BaseBuilder< T,B>> {
public B setB1(String b1){
this.b1 = b1;
return(B)this; //我可以让这个不受控制的演员离开吗?
}
abstract public T build();
字符串b1;
}
并且没有,答案不是:
return B.class.cast(this);
是的,我知道我可以使用@SuppressWarnings
如前所述,这是无法完成的,因为它不安全。 B 扩展
BaseBuilder
,但 BaseBuilder< T,B> code>(类型
this
)不会扩展 B
。递归边界在Java中几乎没有用,并且不会给你自我类型。您可以删除它。
您可以添加一个抽象方法,以便实现类必须提供一个 B
:
public abstract class BaseBuilder< T,B> {
abstract public B getB();
public B setB1(String b1){
this.b1 = b1;
return getB();
}
abstract public T build();
字符串b1;
}
Is there a way to avoid the unchecked class cast in this hierarchical Builder pattern?
public abstract class BaseBuilder <T, B extends BaseBuilder<T,B>> {
public B setB1(String b1) {
this.b1 = b1;
return (B) this; // can I make this unchecked cast go away?
}
abstract public T build();
String b1;
}
and no, the answer is not:
return B.class.cast(this);
and yes, I know I could use @SuppressWarnings
As said before, this can't be done, because it is not safe. B
extends BaseBuilder<T,B>
, but BaseBuilder<T,B>
(type of this
) does not extend B
. Recursive bounds are almost NEVER useful in Java, and do not give you the self-type. You should get rid of it.
You can add an abstract method such that implementing classes must give an instance of B
:
public abstract class BaseBuilder <T, B> {
abstract public B getB();
public B setB1(String b1) {
this.b1 = b1;
return getB();
}
abstract public T build();
String b1;
}
这篇关于Java在层次化构建器模式中避免类转换警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!