[英]return a specific type when Object is the return type in a method in Java
我有這樣的方法getValue
public Object getValue() {
return Integer.valueOf(0);
}
並在main方法中進行調用:
getValue() + 5;
這被簡化了。
如何在不使用main方法進行強制轉換的情況下使此工作正常運行,而是在可能的情況下如何強制轉換返回類型?
您可以使用泛型:
public class MyClass<T extends Number>{
public T getValue(){
//do something here
}
}
MyClass<Integer> foo = new MyClass<Integer>();
foo.getValue()+5;
如果您的方法返回一個Object,則您將不得不在某個時候進行強制轉換,才能使用Integer,Double等類的特定於函數的函數。
我猜您不應該這樣做,如果您編寫了此函數public Object getValue(),那么為什么不將其更改為public Integer getValue()並返回Integer。
如果還期望其他類型,則重載方法public String getValue(),public Double getValue()等。使用工廠模式來確定要調用的方法。
如果您不想轉換,則不能使用Object作為返回類型,而仍然使用getValue()+ 5;。
我也喜歡elivine的回應
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.