Java Reflection for Constructors


Create entities package and create new class named Student as below:

package entities;

public class Student {

	private String id;
	private String name;
	private int age;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public Student() {
	}

	public Student(String id) {
		this.id = id;
	}

	public Student(String id, String name) {
		this.id = id;
		this.name = name;
	}

	public Student(String id, String name, int age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}

}




package reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Parameter;
import entities.Student;

public class Main {

	private static void displayConstructors(Student student) {
		Class studentClass = student.getClass();
		for (Constructor constructor : studentClass.getConstructors()) {
			System.out.println(constructor.getName());
			System.out.println("\tParameter Count: " + constructor.getParameterCount());
			if (constructor.getParameterCount() > 0) {
				for (Parameter parameter : constructor.getParameters()) {
					System.out.println("\t" + parameter.getName() + ": " + parameter.getType());
				}
			}
		}
	}

	public static void main(String[] args) {

		Student student = new Student();
		displayConstructors(student);

	}

}
entities.Student
	Parameter Count: 0
entities.Student
	Parameter Count: 1
	arg0: class java.lang.String
entities.Student
	Parameter Count: 2
	arg0: class java.lang.String
	arg1: class java.lang.String
entities.Student
	Parameter Count: 3
	arg0: class java.lang.String
	arg1: class java.lang.String
	arg2: int