Reputation: 663
I know there are various capabilities in Java with reflection. For example:
Class<?> clazz = Class.forName("java.util.Date");
Object ins = clazz.newInstance();
I wonder if I could pass class dynamicaly in some method declaration in <> tags (or there is other way to do it if it must be fixed). I would like to change that class declaration dynamicaly; because I would like to write generic method for all types of classes.
In there, I have this:
List<Country>
Can I write it something diffrent with reflection? For example can it be somehow be achieved to pass class as parameter (or how else should be this done):
List<ins>
? I would appreciate examples.
Upvotes: 0
Views: 80
Reputation: 54584
Generics are there so that the compiler can verify correct typing, but are no longer present at runtime (this is called "type erasure"). Reflection deals with the runtime representation of types only. As far as I know the only case where reflection has to deal with generics is to find out "fixed" type parameters of sub-classes, e.g. when you have class Bar<T>
and class Foo extends Bar<String>
, you can find out that the T
of Bar
is fixed to String
in Foo
using reflection. However, this is information found in the class file, too. Except that, reflection can only see or create raw-types.
Upvotes: 0
Reputation: 18834
This cannot be done because generics are a compile time feature. Once code is compiled, the only place where generics are exists are at method signatures, and they are only used for compiling new code.
When working with reflection, you are basicly working with raw types, and need to code according to that, that means, you can cast the returned result of newInstance()
to the list type your need, for example:
List<Country> ins = (List<Country>)clazz.newInstance();
This is a safe operation to do, because you know at that point its empty, and isn't passed to any outside code.
Upvotes: 1
Reputation: 8215
I don't think this is possible. Generics in Java are implemented in a way that prohibits runtime access.
Upvotes: 0