Is it possible to automatically infer the return type if I give an Enum as parameter to a method in Java?
I would like to be able to support these calls by making getValue generic and using information in the Enum
String myval = obj.getValue(MyEnum.Field1)
int myval2 = obj.getValue(MyEnum.Field2)
Current solution
My current solution does like this:
String val = typeRow.getColumnValueGen(TYPEGODKENDCRM.COLUMN_TYPEGODKENDNR, String.class)
It’s for accessing columns in a ORM representation of a table. I known that this field is a string, I would like to avoid having to tell it at every call.
No. You can’t overload methods by return type in Java, and if you wanted something like:
there’s no way for the compiler to infer
Tbased on the argument. Type inference can work in some cases, but not like this. There’s no way for the compiler to examine some aspect of the argument and infer or even validate the type based on that value.Aside from anything else, what would you expect it to do if the argument weren’t a compile-time constant?
Basically you would have to cast the return value… and in the case of
int, you’d need to cast toIntegerrather thanint, and then let auto-unboxing do the rest.Personally I’d just create multiple methods:
That leaves no room for ambiguity, doesn’t require any cleverness with generics etc.