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.
Is it possible to automatically infer the return type if I give an Enum as parameter to a method in Java?
No. You can't overload methods by return type in Java, and if you wanted something like:
public <T> T getValue(MyEnum enumValue)
there's no way for the compiler to infer T
based 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?
MyEnum x = getEnumValue();
// Is this valid or not?
String myVal = obj.getValue(x);
Basically you would have to cast the return value... and in the case of int
, you'd need to cast to Integer
rather than int
, and then let auto-unboxing do the rest.
Personally I'd just create multiple methods:
String x = obj.getString(...);
int y = obj.getInt(...);
That leaves no room for ambiguity, doesn't require any cleverness with generics etc.
In a word: No. You'd have to declare getValue as returning Object and then cast the returned object to the actual type. Not pretty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With