We can use newInstance API of java.lang.reflect.Constructor to create Objects. We can pass initialization parameters to the parameterized Constructors.
Instantiate a new object without no args constructor
Class < ReflectionCreateObjects > clazz = ReflectionCreateObjects . class ;
Constructor < ReflectionCreateObjects > constructor = clazz. getConstructor ( ) ;
ReflectionCreateObjects obj = constructor. newInstance ( ) ;
Copy
Instantiate a new object with parameterized constructor
Class < ReflectionCreateObjects > clazz = ReflectionCreateObjects . class ;
Constructor < ReflectionCreateObjects > constructor1 = clazz. getConstructor ( String . class ) ;
ReflectionCreateObjects obj1 = constructor1. newInstance ( "testVar" ) ;
Copy
Instantiate a new object with Class object
Please note that Class.newInstance() can only invoke the no-arg constructor.
Class < ReflectionCreateObjects > clazz = ReflectionCreateObjects . class ;
ReflectionCreateObjects obj2 = clazz. newInstance ( ) ;
Copy
Java Code - Full Example
package com. java. reflection ;
import java. lang. reflect. Constructor ;
import java. lang. reflect. InvocationTargetException ;
public class ReflectionCreateObjects {
@Override
public String toString ( ) {
return "ReflectionCreateObjects [var=" +
var + "]" ;
}
private String
var ;
public ReflectionCreateObjects ( String
var ) {
this . var =
var ;
}
public ReflectionCreateObjects ( ) { }
public static void main ( String [ ] args) {
Class < ReflectionCreateObjects > clazz = ReflectionCreateObjects . class ;
Constructor < ReflectionCreateObjects > constructor;
Constructor < ReflectionCreateObjects > constructor1;
try {
constructor = clazz. getConstructor ( ) ;
ReflectionCreateObjects obj = constructor. newInstance ( ) ;
System . out. println ( obj) ;
constructor1 = clazz. getConstructor ( String . class ) ;
ReflectionCreateObjects obj1 = constructor1. newInstance ( "testVar" ) ;
System . out. println ( obj1) ;
ReflectionCreateObjects obj2 = clazz. newInstance ( ) ;
System . out. println ( obj2) ;
} catch ( NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException |
IllegalArgumentException | InvocationTargetException e) {
e. printStackTrace ( ) ;
}
}
}
Copy
Output
ReflectionCreateObjects [ var = null ]
ReflectionCreateObjects [ var = testVar]
ReflectionCreateObjects [ var = null ]
Copy
Related Article
Java Reflection : Interview questions