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'
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In Java 9 and afterward, if there’s a declared zero-parameter (“nullary”) constructor, you’d use
Class.getDeclaredConstructor()to get it, then callnewInstance()on it:Prior to Java 9, you would have used
Class.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.newInstancewraps exceptions from the constructor inInvocationTargetExceptioninstead.Both of the above assume there’s a zero-parameter constructor. A more robust route is to go through
Class.getDeclaredConstructorsorClass.getConstructors, which takes you into using the Reflection stuff in thejava.lang.reflectpackage, to find a constructor with the parameter types matching the arguments you intend to give it.