1

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?

3
  • 1
    Why do you need this specifically ? Commented Jul 8, 2015 at 8:50
  • There is no way to get the class of a generic. Look in all examples they always do somthing like Foo<Integer> foo = new Foo<Integer>(Integer.class) Commented Jul 8, 2015 at 8:52
  • Foo<Integer>.class has no sense in Java due to type erasure: you only have the Foo type. Commented Jul 8, 2015 at 8:58

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

.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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.