0

I'm having troubles trying to find a solution, if any, to this:

public class Generics {
    Map<Class<? extends SomeObject1>, SomeObject2>> map;
    map = new HashMap<Class<? extends SomeObject1>, SomeObject2>>();

    public static <E extends SomeObject1> SomeObject2 get(Class<E> c) {
        if (map.containsKey(c))
           return map.get(c);
        else {
           SomeObject2 o = new SomeObject2();
           map.put(c, o);
           return o;
        }
    }
}
...
//somewhere
public <T extends SomeObject1> void aMethod(AnInterestedClass<T> list) {
    // How to get the value from the map
    // knowing that the key is of type T?
    Generics.get(); 
}

Ideas?

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
Sebastian
  • 4,770
  • 4
  • 42
  • 43
  • Duplicate: http://stackoverflow.com/questions/1353901/is-there-a-way-to-find-the-type-of-a-template-generic-parameter-in-java – jalopaba Jun 21 '12 at 07:51
  • @jalopaba, I don't think it's a duplicate. Actually I'm using this mapping without any problem: ´Generics.get(SomeObject1.class);´. The question arises as a new need I have in the project (the ´aMethod()´ example). Evidently, the codeMangle question was somekind misleading with its needs and solution. The answer is what relates this question though. Thanks anyway. – Sebastian Jun 21 '12 at 08:00

1 Answers1

1

Because of type erasure, you can only do this by passing a Class object to aMethod. See this related thread.

Community
  • 1
  • 1
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • I had previosly read [this](http://stackoverflow.com/questions/182636/how-to-determine-the-class-of-a-generic-type) trying to find a solution to the problem. But reading your comment makes me search a different approach. Thanks. – Sebastian Jun 21 '12 at 08:05