简体   繁体   中英

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

I have a method getValue like this

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

}

and a call in the main method:

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?

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.

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.

If you dont want to cast then you can't use Object as return type and still use getValue() + 5;

I also like elivine's response

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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