Print/list public/protected/private constructors of class in java (example)

By | February 26, 2017
  1. Given a class in java containing public,private & protected contructors.
  2. Get/list/print all constructors (prive,protected & public) of a class using Class.
    • getConstructors method of Class will list all public constructors of given class.
    • getDeclaredConstructors method of Class will list all private, protected & public constructors
No.Method Name Description
1Constructor<?>[] getConstructors() Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object.
2Constructor<?>[] getDeclaredConstructors() Returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object.

1. Print/list public/protected/private constructors of class in java (example)

package org.learn.classes;

import java.lang.reflect.Constructor;
import java.util.Date;

class Vehicle {
    private String owner;
    private float cost;
    private String model;

    private Vehicle() {

    }

    protected Vehicle(String owner, float cost) {
        this.owner = owner;
        this.cost = cost;
    }

    public Vehicle(String owner, float cost, String model) {
        this.owner = owner;
        this.cost = cost;
        this.model = model;
    }
}

public class DemoGetClassConstructors {

    public static void main(String[] args) {

        final Constructor<?>[] allConstructors = Vehicle.class.getConstructors();

        System.out.println("1. Get public constructors of Vehicle class");
        for (Constructor constructor : allConstructors) {
            System.out.println(constructor);
        }
        System.out.println("2. End - public constructors of Vehicle class");
        System.out.println();

        System.out.println("3. Get all declared (private,protected,public) constructors of Vehicle class");
        final Constructor<?>[] declaredConstructors = Vehicle.class.getDeclaredConstructors();
        for (Constructor constructor : declaredConstructors) {
            System.out.println(constructor);
        }
        System.out.println("4. End - all declared constructors of Vehicle class");
    }
}

2. Output: public/protected/private constructors of class in java (example)

 1. Get public constructors of Vehicle class
public org.learn.classes.Vehicle(java.lang.String,float,java.lang.String)
2. End get public constructors of Vehicle class

3. Get all declared (private,protected,public) constructors of Vehicle class
private org.learn.classes.Vehicle()
protected org.learn.classes.Vehicle(java.lang.String,float)
public org.learn.classes.Vehicle(java.lang.String,float,java.lang.String)
4. End Get all declared constructors of Vehicle class