Parameterizing the return type of a method using an enum -- possible?
In java, I know it's possible to e.g.:
static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
for (T o : a) {
c.add(o); // Correct
}
}
In my scenario, I have an enumeration of different settings I can retrieve a value for, where each setting has a different value type. I'd like to specify these value types in the enumeration, and get compile-time checking similar to the above.
Here is a version with runtime checking -- is compile-time checking possible?
public class Foo {
public static enum ClientSetting {
SOME_STRING_SETTING(String.class),
SOME_INTEGER_SETTING(Integer.clas开发者_Go百科s);
private Class valueClass;
ClientSetting(Class valueClass) {
this.valueClass = valueClass;
}
}
public static <T> T get(ClientSetting bar) {
if (bar.valueClass.equals(String.class))
return (T) "My string value.";
else if (bar.valueClass.equals(Integer.class))
return (T) new Integer(2);
else
return null; // unreachable if every possibility is checked
}
public static void main(String[] args) {
String stringValue = get(ClientSetting.SOME_STRING_SETTING);
Integer integerValue = get(ClientSetting.SOME_INTEGER_SETTING);
}
}
Thanks!
dacc, would something like this work for you?
public static class ClientSetting<T> {
private T setting;
ClientSetting(T setting) {
this.setting = setting;
}
public T get() {
return setting;
}
}
// Old school, I know.
public static final ClientSetting<String> SOME_STRING_SETTING =
new ClientSetting<String>("My string value.");
public static final ClientSetting<Integer> SOME_INTEGER_SETTING =
new ClientSetting<Integer>(2);
public static <T> T get(ClientSetting<T> clientSetting) {
// delegation, this method is not really needed
// you can go for SOME_STRING_SETTING.get()
return clientSetting.get();
}
public static void main(String[] args) {
String stringValue = get(SOME_STRING_SETTING);
Integer integerValue = get(SOME_INTEGER_SETTING);
// Won't compile
// String wrong = get(SOME_INTEGER_SETTING);
}
I'm not sure if this would help, but what if you put a generic on ClientSetting? You could pass around ClientSetting<String>
or ClientSetting<Integer>
. Assuming you were coding to a specific one of these, some compile-time checking would occur.
精彩评论