Reputation: 1915
Say I have a Type a
which is a java.util.TreeSet<T>
, having been parameterized via a generic we can't see due to type erasure. We also have a Type b
, which is a 'java.lang.Integer'. How do I construct a ParameterizedType
that is a java.util.TreeSet<java.lang.Integer>
?
Alternatively, if it's any easier, we could have a raw java.util.TreeSet
type to work with.
Upvotes: 0
Views: 117
Reputation: 2295
Implement ParameterizedType
like so:
public class MyParamType implements ParameterizedType {
private Type rawType;
private List<Type> paramTypes;
public MyParamType( Type raw ) {
this.rawType = raw;
}
public void addParamType( Type t ) {
paramTypes.add(t);
}
//for the interface methods, just return what you stored before
}
Do more or less the same for Type
.
If you need more hints for what Type
should actually implement for non-generic types (it's only a marker interface), look at the JDK source or look at a concrete instance in the debugger.
Upvotes: 1
Reputation: 115328
You gave half of the answer to your own question. The type parameter (Integer in your case) is an erasure existing at compile time only. So, if you want to create Set<Integer>
while you are developing your code you just can say:
Set<Integer> myset = new TreeSet<Integer>();
or if you are lucky Java 7 user even shorter:
Set<Integer> myset = new TreeSet<>();
However this line will be compiled to plain code:
Set myset = new TreeSet();
So, if you want to create instance of TreeSet<Integer>
at runtime you just have to create instance of plain TreeSet
, e.g. Class.forName(className).newInstance()
. Type parameter Integer
is irrelevant in this case.
EDIT:
I just have read your comment and understood why are you asking. If you really want you can create subclass of TreeSet
: class IntegerTreeSet extends TreeSet<Integer>
. The parameter type of IntegerTreeSet
can be discovered using reflection API.
This class can be either created statically (just write this in your code) or dynamically using tools like Javassist or CGLIB.
Upvotes: 0