22

In java, can I use a class object to dynamically instantiate classes of that type?

i.e. I want some function like this.

Object foo(Class type) {
    // return new object of type 'type'
}
akula1001
  • 4,576
  • 12
  • 43
  • 56

4 Answers4

36

In Java 9 and afterward, if there's a declared zero-parameter ("nullary") constructor, you'd use Class.getDeclaredConstructor() to get it, then call newInstance() on it:

Object foo(Class type) throws InstantiationException, IllegalAccessException, InvocationTargetException {
    return type.getDeclaredConstructor().newInstance();
}

Prior to Java 9, you would have used Class.newInstance:

Object foo(Class type) throws InstantiationException, IllegalAccessException {
    return type.newInstance();
}

...but it was deprecated as of Java 9 because it threw any exception thrown by the constructor, even checked exceptions, but didn't (of course) declare those checked exceptions, effectively bypassing compile-time checked exception handling. Constructor.newInstance wraps exceptions from the constructor in InvocationTargetException instead.

Both of the above assume there's a zero-parameter constructor. A more robust route is to go through Class.getDeclaredConstructors or Class.getConstructors, which takes you into using the Reflection stuff in the java.lang.reflect package, to find a constructor with the parameter types matching the arguments you intend to give it.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

Use:

type.newInstance()

For creating an instance using the empty costructor, or use the method type.getConstructor(..) to get the relevant constructor and then invoke it.

Eyal Schneider
  • 22,166
  • 5
  • 47
  • 78
1

Yes, it is called Reflection. you can use the Class newInstance() method for this.

akf
  • 38,619
  • 8
  • 86
  • 96
  • You can read more about it at: http://java.sun.com/docs/books/tutorial/reflect/index.html Also this post has very good information: http://stackoverflow.com/questions/37628/what-is-reflection-and-why-is-it-useful – RonK Jun 14 '10 at 11:27
-1

use newInstance() method.

GG.
  • 2,835
  • 5
  • 27
  • 34