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'
}
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'
}
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.
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.
Yes, it is called Reflection. you can use the Class newInstance()
method for this.