I ve searched for answers here and every thread I found were in fact "fragments" of what I seek.
I d like to find a better way than this :
~ EDIT: OOPS ! I meant to use primitive Wrapper classes in the first place, but I was thinking of using primitive types when calling the method at that very moment~ Thank you for noticing it :)
@Override
public void setValue(Object value) {
if (value instanceof String) {
} else if (value instanceof Integer) { // and not int
} else if (value instanceof Long) { // and not long
}
}
// The usage that made me confused in the first place :
int i = 42;
setValue(i);
通知@Override annotation:这是采用接口方法。 这种方法将接受不同的执行类型,因此我不想采用不同的参数类型来制造三种不同的方法。
举例来说,这只是一个案文箱,只接受数字和任何其他东西,因此,它只能由长处和直线的“固定表述”(由定期的<<条码>[0-9]*条码>验证)。
我也喜欢——或许是,最终——接受更像日本国际协力事业团这样的习俗(和简单),但如果这种特殊性使一切变得复杂的话,我会想到其他事情,那不会对此感到太多的担忧。
正如我说过的那样,这一接口的不同实施可能完全不同。
∗∗∗ 显然,我并没有要求转手案件Integers、Longs和Sting(但不能开关)。 直到 Java7(即)为止,我想转而谈一下:。
研究了
- java: boolean instanceOf Boolean?
- switch instanceof?
- Autoboxing : http://leepoint.net/notes-java/data/basic_types/autoboxing.html
My implementation obviously works, but I just feel there s a better way. I am wondering if there is a cleaner method than doing what I did, what do you suggest and why?
Thank you for your time. Sincerely, Dominic Brissette.
<>strong>EDIT: 使用原始类型和自动箱
public static void main(String[] args) {
int i = 42;
System.out.println(autoboxing(i));
}
public static boolean autoboxing(Object o) {
return o instanceof Integer;
}
产出<代码>true,因为末,my Int instance of Integer
iskinda real.!