//Sample class Student.java
public class Student {
private Integer sudentId;
private String studentName;
private Student(){}
private Student(Integer studentId, String studentName) {
this.studentId = studentId;
this.studentName = studentName;
}
public Integer getStudentId() {
return studentId;
}
public String getStudentName() {
return studentName;
}
}
In below code, There are two ways to instantiate the class
1- Find the private constructor using given constructor name and instantiate the class. 2- Find the private constructor for given number of arguments and types and instantiate the class
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
public class PrivateConstructorDemo {
//Find the private constructor using given constructor name and instantiate the class.
public void createObjectByConstructorName(int id, String name) throws NoSuchMethodException, SecurityException,
InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
Constructor<Student> constructor = Student.class.getDeclaredConstructor(Integer.class, String.class);
if (Modifier.isPrivate(constructor.getModifiers())) {
constructor.setAccessible(true);
Student student = (Student)constructor.newInstance(id, name);
System.out.println("Student Id:"+ student.getStudentId());
System.out.println("Student Name:"+ student.getStudentName());
}
}
//For given number of arguments and types and instantiate the class.
public void createObject(int id, String name) throws InstantiationException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Constructor<?>[] constructors = Student.class.getDeclaredConstructors();
for (Constructor<?> constructor : constructors) {
if (Modifier.isPrivate(constructor.getModifiers())) {
constructor.setAccessible(true);
Class<?>[] clazzs = constructor.getParameterTypes();
if (constructor.getParameterCount() == 2 && clazzs[0] == Integer.class &&
clazzs[1] == String.class) {
Object ob = constructor.newInstance(id, name);
if (ob instanceof Student) {
Student student = (Student)ob;
System.out.println("Student Id:"+ student.getStudentId());
System.out.println("Student Name:"+ student.getStudentName());
}
}
}
}
}
public static void main(String[] args) throws InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
PrivateConstructorDemo obj = new PrivateConstructorDemo();
obj.createObject(10, "Sandeep");
System.out.println("-------------------------");
obj.createObjectByConstructorName(20,"Sandeep");
}
}
Aucun commentaire:
Enregistrer un commentaire