通用或代替和&lt;吨延伸号| CharSequence的&GT; [英] Generic OR instead of AND <T extends Number | CharSequence>
问题描述
是否有可能一般参数的方法接受无论是ClassA的或InterfaceB?
不编译由于|伪code
公开&LT;吨延伸号| CharSequence的&GT;无效orDoer(T someData){// ...}
即。而不是写多个方法签名,我想这个方法接受一个数字或CharSequence中作为参数
如果以数字或CharSequence参数传递
orDoer(新的整数(6));
INT somePrimitive = 4;
orDoer(somePrimitive);
orDoer(字符的字符串);
如果您真的要做到这一点,你需要来包装自己的自定义类中youur接受类。在您的例子的情况下,大概是这样的:
公共类OrDoerElement {
私人最终数量numberValue;
私人最终的CharSequence charSequenceValue;
私人OrDoerElement(数数,CharSequence中的CharSequence){
this.numberValue =号;
this.charSequenceValue = CharSequence的;
}
公共静态OrDoerElement fromCharSequence(CharSequence的值){
返回新OrDoerElement(NULL,值);
}
公共静态OrDoerElement fromNumber(数字值){
返回新OrDoerElement(值null);
}
}
和您的 orDoer
方法就变成了:
公共无效orDoer(OrDoerElement someData){....}
然后就可以建立这些之一,并使用你的方法请使用:
orDoer(OrDoerElement.fromCharSequence(字符的字符串));
orDoer(OrDoerElement.fromNumber(新的整数(6)));
不过说实话,这听起来有点太复杂,太多的工作只是为了能够调用不同的参数类型的方法。您使用的两种方法,并为共同的逻辑第三种方法肯定不能达到同样的?
Is it possible to generically parameterize a method accepting EITHER ClassA OR InterfaceB ?
Does Not Compile Due to | Pseudocode
public <T extends Number | CharSequence> void orDoer(T someData){ // ... }
i.e. instead of writing multiple method signatures, I would like this one method to accept either a Number or CharSequence as an argument
Should Pass with a Number OR CharSequence argument
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);
}
}
And your orDoer
method becomes:
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?
这篇关于通用或代替和&lt;吨延伸号| CharSequence的&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!