Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instantiate class from class object

Tags:

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' } 
like image 355
akula1001 Avatar asked Jun 14 '10 11:06

akula1001


People also ask

How do you instantiate a class object?

Instantiating a ClassThe new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object. The new operator returns a reference to the object it created.

Can we instantiate object class?

Instantiating a Class The new operator also invokes the object constructor. Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.

How do you instantiate a class object in Java?

Java provides the new keyword to instantiate a class. We can also instantiate the above class as follows if we defining a reference variable. We observe that when we use the new keyword followed by the class name, it creates an instance or object of that class.

Why do we instantiate an object of a class?

"A class i.e. created inside a method is called local inner class in java. If you want to invoke the methods of local inner class, you must instantiate this class inside the method". The word in bold.


1 Answers

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.

like image 121
T.J. Crowder Avatar answered Oct 08 '22 22:10

T.J. Crowder