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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10150414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:48:56  来源:igfitidea点击:

return a specific type when Object is the return type in a method in Java

javaobjectmethodsreturn

提问by Kristian Vukusic

I have a method getValuelike 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 方法的情况下使其工作,而是如何在可能的情况下转换返回类型?

回答by Eric Levine

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;

回答by lrAndroid

If your method returns an Object, you're going to have to cast at some point or another to use the class specific functions of Integer, Double, etc.

如果您的方法返回一个对象,您将不得不在某个时间点进行强制转换,以使用 Integer、Double 等类的特定函数。

回答by srisris

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 的回复