Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically infer return type using enum parameter

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.

like image 827
Per Stilling Avatar asked Dec 26 '22 10:12

Per Stilling


2 Answers

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.

like image 71
Jon Skeet Avatar answered Jan 04 '23 21:01

Jon Skeet


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.

like image 24
mwittrock Avatar answered Jan 04 '23 20:01

mwittrock