Creating parameterized type object using annonymous class
Posted
by Andrei Fierbinteanu
on Stack Overflow
See other posts from Stack Overflow
or by Andrei Fierbinteanu
Published on 2010-06-07T12:34:15Z
Indexed on
2010/06/07
13:02 UTC
Read the original article
Hit count: 204
This might be a stupid question, but I just saw a question asking how to create a Type variable for a generic type. The consensus seemed to be that you should have a dummy method returning that type, and then use reflection to get it (in this case he wanted Map<String, String>
). Something like this :
public Map<String, String> dummy() { throw new Error(); }
Type mapStringString = Class.forName("ThisClass").getMethod("dummy").getGenericReturnType();
My question is, not having used reflection that much, couldn't you just do something like:
Type mapStringString = new ParameterizedType() {
public Type getRawType() {
return Map.class;
}
public Type getOwnerType() {
return null;
}
public Type[] getActualTypeArguments() {
return new Type[] { String.class, String.class };
}
};
Would this work? If not, why not? And what are some of the dangers/problems if it does (besides being able to return some Type like Integer<String>
which is obviously not possible.
© Stack Overflow or respective owner