Call overloaded constructors using reflection
suggest changeExample: Invoke different constructors by passing relevant parameters
import java.lang.reflect.*;
class NewInstanceWithReflection{
public NewInstanceWithReflection(){
System.out.println("Default constructor");
}
public NewInstanceWithReflection( String a){
System.out.println("Constructor :String => "+a);
}
public static void main(String args[]) throws Exception {
NewInstanceWithReflection object = (NewInstanceWithReflection)Class.forName("NewInstanceWithReflection").newInstance();
Constructor constructor = NewInstanceWithReflection.class.getDeclaredConstructor( new Class[] {String.class});
NewInstanceWithReflection object1 = (NewInstanceWithReflection)constructor.newInstance(new Object[]{"StackOverFlow"});
}
}
output:
Default constructor
Constructor :String => StackOverFlow
Explanation:
- Create instance of class using
Class.forName
: It calls default constructor - Invoke
getDeclaredConstructor
of the class by passing type of parameters asClass array
- After getting the constructor, create
newInstance
by passing parameter value asObject array
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents