通用 OR 而不是 AND <T extends Number |字符序列> [英] Generic OR instead of AND <T extends Number | CharSequence>
问题描述
是否可以对接受 ClassA 或 InterfaceB 的方法进行一般参数化?
Is it possible to generically parameterize a method accepting EITHER ClassA OR InterfaceB ?
不编译由于 |伪代码
public <T extends Number | CharSequence> void orDoer(T someData){ // ... }
即而不是编写多个方法签名,我希望这个方法接受一个 Number 或 CharSequence 作为参数
i.e. instead of writing multiple method signatures, I would like this one method to accept either a Number or CharSequence as an argument
应该传递一个 Number OR CharSequence 参数
orDoer(new Integer(6));
int somePrimitive = 4;
orDoer(somePrimitive);
orDoer("a string of chars");
推荐答案
如果您真的想要这样做,您需要将您接受的类包装在您自己的自定义类中.在您的示例中,可能类似于:
If you really want to do that, you'll need to wrap youur accepted classes inside a custom class of your own. In your example case, probably something like:
public class OrDoerElement {
private final Number numberValue;
private final CharSequence charSequenceValue;
private OrDoerElement(Number number, CharSequence charSequence) {
this.numberValue = number;
this.charSequenceValue = charSequence;
}
public static OrDoerElement fromCharSequence(CharSequence value) {
return new OrDoerElement(null, value);
}
public static OrDoerElement fromNumber(Number value) {
return new OrDoerElement(value, null);
}
}
你的 orDoer
方法变成:
public void orDoer(OrDoerElement someData) { .... }
然后您可以构建其中一个并使用以下任一方法在您的方法中使用:
Then you can build one of those and use in your method using either:
orDoer(OrDoerElement.fromCharSequence("a string of chars"));
orDoer(OrDoerElement.fromNumber(new Integer(6)));
但老实说,仅仅为了能够调用具有不同参数类型的方法,这听起来有点太复杂和太多的工作.你确定你不能用两种方法来达到同样的效果,而用第三种方法来实现通用逻辑吗?
But honestly, that sounds a bit too complex and too much work just to be able to call a method with different parameter types. Are you sure you can't achieve the same using two methods, and a third method for the common logic?
这篇关于通用 OR 而不是 AND <T extends Number |字符序列>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!