I'm trying to create a generic type that keeps a map of the versions of itself that have been created for later use. Effectively, it's an singleton pattern where there's one instance per type. The code I have so far is:
public class FieldBinder<T> {
static final Map<Class<? extends Object>,FieldBinder<? extends Object>> instanceMap =
new HashMap<Class<? extends Object>,FieldBinder<? extends Object>>();
private FieldBinder() {}
synchronized public static <V extends Object> FieldBinder<V> getInstance(Class<V> klass) {
if(!instanceMap.containsKey(klass)) {
instanceMap.put(klass, new FieldBinder<V>());
}
return (FieldBinder<V>)instanceMap.get(klass);
}
}
However, I'm still unsure that I'm "doing it right". It feels like I should be able to specify that the collection is (Class -> FieldBinder). The fact that the IDE is warning about the return statement only reinforces this thought.
Is there a better way to handle this?
Note: This question seems very closely related, but just far enough away that I can't figure out how to apply the information in it to my own problem.
Your implementation is correct. There's no "better" way of doing it (if there is such a thing is "better" in code, which is another issue..)
Minor fixes:
<V extends Object>
is equivalent to V
which is less verboseClass<? extends Object>
is equivalent to Class<?>
which is less verbose@SuppressWarnings("unchecked")
annotation to tell your compiler that the cast is safeIf 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