Reputation: 1197
In Java, if I have:
public class Foo<T> {
public Foo() { }
}
I can do Foo<Integer> foo = new Foo<Integer>();
but I cannot find an equivalent syntax for using the class
field, meaning that something like Foo<Integer> foo = Foo<Integer>.class.newInstance();
doesn't work. Is there a way to use generics via the newInstance method?
Upvotes: 1
Views: 150
Reputation: 122489
.newInstance()
(and anything that uses Class
) is a reflection API that fundamentally works at runtime. Therefore it has little to do with Generics which operates at compile-time.
Upvotes: 1
Reputation: 26084
You can do it only without parameterized type. Class.newInstance()
is not quite recommendable. You can do this:
//Class<Foo<Integer>> clazz = Foo<Integer>.class; <-- Error
Class<Foo> clazz = Foo.class; // <-- Ok
Foo instance = clazz.getConstructor().newInstance();
Why is Class.newInstance() evil?
Hope it helps.
Upvotes: 1
Reputation: 21224
newInstance()
is an API from the early days of Java - no generics back then. You have to cast the return value.
Also: there will be no future method doing that, newInstance()
is used to create objects dynamically at runtime. Due to type erasure in Java there is no generic information at runtime anymore.
Upvotes: 0