Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Map of Generic key/values with related types

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.

like image 212
RHSeeger Avatar asked Feb 05 '10 15:02

RHSeeger


1 Answers

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 verbose
  • Class<? extends Object> is equivalent to Class<?> which is less verbose
  • You can use the @SuppressWarnings("unchecked") annotation to tell your compiler that the cast is safe
like image 145
Itay Maman Avatar answered Oct 26 '22 16:10

Itay Maman