views:

68

answers:

4

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'
}
+2  A: 

You can use Class.newInstance:

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

...but that assumes there's a zero-argument constructor. A more robust route is to go through Class.getConstructor or Class.getConstructors, which takes you into using the Reflection stuff in the java.lang.reflect package.

T.J. Crowder
+1  A: 

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
+1  A: 

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

akf
You can read more about it at: http://java.sun.com/docs/books/tutorial/reflect/index.htmlAlso this post has very good information: http://stackoverflow.com/questions/37628/what-is-reflection-and-why-is-it-useful
RonK
A: 

use newInstance() method.

GG