简体   繁体   English

当Object是Java方法中的返回类型时,返回特定类型

[英]return a specific type when Object is the return type in a method in Java

I have a method getValue like this 我有这样的方法getValue

public Object getValue() {
     return Integer.valueOf(0);

} }

and a call in the main method: 并在main方法中进行调用:

getValue() + 5;

This is simplified. 这被简化了。

How to get this working without casting in the main method, but instead how to cast the return type if possible? 如何在不使用main方法进行强制转换的情况下使此工作正常运行,而是在可能的情况下如何强制转换返回类型?

You could use generics: 您可以使用泛型:

public class MyClass<T extends Number>{


  public T getValue(){
    //do something here
  }
}

MyClass<Integer> foo = new MyClass<Integer>();
foo.getValue()+5;

如果您的方法返回一个Object,则您将不得不在某个时候进行强制转换,才能使用Integer,Double等类的特定于函数的函数。

I guess you should not do that, if you wrote this function public Object getValue() then why not change it to public Integer getValue() and return Integer. 我猜您不应该这样做,如果您编写了此函数public Object getValue(),那么为什么不将其更改为public Integer getValue()并返回Integer。

If you also expect other types then over load the method public String getValue(), public Double getValue() etc. Use factory pattern to decide which method to call. 如果还期望其他类型,则重载方法public String getValue(),public Double getValue()等。使用工厂模式来确定要调用的方法。

If you dont want to cast then you can't use Object as return type and still use getValue() + 5; 如果您不想转换,则不能使用Object作为返回类型,而仍然使用getValue()+ 5;。

I also like elivine's response 我也喜欢elivine的回应

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM