How do I get constructors of a class object?

Below is an example that showing you how to get constructors of a class object. In the code below we get the constructors by calling the Class.getDeclaredConstructors() or the Class.getConstructor(Class[]) method.

package org.kodejava.lang.reflect;

import java.lang.reflect.Constructor;

public class GetConstructors {
    public static void main(String[] args) {
        Class<String> clazz = String.class;

        // Get all declared constructors and iterate the constructors to get their
        // name and parameter types.
        Constructor<?>[] constructors = clazz.getDeclaredConstructors();
        for (Constructor<?> constructor : constructors) {
            String name = constructor.getName();
            System.out.println("Constructor name= " + name);

            Class<?>[] parameterTypes = constructor.getParameterTypes();
            for (Class<?> c : parameterTypes) {
                System.out.println("Param type name = " + c.getName());
            }
            System.out.println("----------------------------------------");
        }

        // Getting a specific constructor of the java.lang.String
        try {
            Constructor<String> constructor = String.class.getConstructor(String.class);
            System.out.println("Constructor     = " + constructor.getName());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}

How do I get field of a class object and set or get its value?

A refection demo to get fields of a class’s object and set or get their values.

package org.kodejava.lang.reflect;

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

public class GetSetFieldDemo {
    public static Date now;
    public Long id;
    public String name;

    public static void main(String[] args) {
        GetSetFieldDemo demo = new GetSetFieldDemo();
        Class<? extends GetSetFieldDemo> clazz = demo.getClass();

        try {
            // Get field id, set it value and read it back
            Field field = clazz.getField("id");
            field.set(demo, 10L);
            Object value = field.get(demo);
            System.out.println("Value = " + value);

            // Get static field date, set it value and read it back
            field = clazz.getField("now");
            field.set(null, new Date());
            value = field.get(null);
            System.out.println("Value = " + value);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }

    }
}

The output of the code snippet:

Value = 10
Value = Wed Oct 06 06:18:23 CST 2021

How do I get fields of a class object?

The example below using reflection to obtain the fields of a class object. We’ll get the field names and their corresponding type. There are three ways shown below which can be used to get an object fields:

  • Class.getDeclaredFields()
  • Class.getFields()
  • Class.getField(String)
package org.kodejava.lang.reflect;

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

public class GetFields {
    public Long id;
    protected String name;
    private Date birthDate;
    Double weight;

    public static void main(String[] args) {
        GetFields object = new GetFields();
        Class<? extends GetFields> clazz = object.getClass();

        // Get all object fields including public, protected, package and private
        // access fields.
        Field[] fields = clazz.getDeclaredFields();
        System.out.println("Number of fields = " + fields.length);
        for (Field field : fields) {
            System.out.println("Field name = " + field.getName());
            System.out.println("Field type = " + field.getType().getName());
        }

        System.out.println("\n----------------------------------------\n");

        // Get all object accessible public fields.
        fields = clazz.getFields();
        System.out.println("Number of fields = " + fields.length);
        for (Field field : fields) {
            System.out.println("Field name = " + field.getName());
            System.out.println("Field type = " + field.getType().getName());
        }

        System.out.println("\n----------------------------------------\n");

        try {
            // Get field name id with public access modifier
            Field field = clazz.getField("id");
            System.out.println("Field name = " + field.getName());
            System.out.println("Field type = " + field.getType().getName());
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}

The output of the code snippet above are:

Number of fields = 4
Field name = id
Field type = java.lang.Long
Field name = name
Field type = java.lang.String
Field name = birthDate
Field type = java.util.Date
Field name = weight
Field type = java.lang.Double

----------------------------------------

Number of fields = 1
Field name = id
Field type = java.lang.Long

----------------------------------------

Field name = id
Field type = java.lang.Long

How do I invoke a method using Method class?

This example demonstrate using reflection to invoke methods of a class object. Using reflection we can call method of an object using the given string name of the method. When using this method we need to catch for the NoSuchMethodException, IllegalAccessException and InvocationTargetException.

package org.kodejava.lang.reflect;

import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;

public class InvokingMethod {
    public static void main(String[] args) {
        InvokingMethod object = new InvokingMethod();
        Class<? extends InvokingMethod> clazz = object.getClass();

        try {
            // Invoking the add(int, int) method
            Method method = clazz.getMethod("add", int.class, int.class);
            Object result = method.invoke(object, 10, 10);
            System.out.println("Result = " + result);

            // Invoking the multiply(int, int) method
            method = clazz.getMethod("multiply", int.class, int.class);
            result = method.invoke(object, 10, 10);
            System.out.println("Result = " + result);

        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public int add(int numberA, int numberB) {
        return numberA + numberB;
    }

    public int multiply(int numberA, int numberB) {
        return numberA * numberB;
    }
}

How do I get the methods of a class object?

In this example we show you how to get the methods available in a class object. We show three ways to get the methods, they are:

  • Class.getDeclaredMethods()
  • Class.getMethods()
  • Class.getMethod(String, Class<?>...)
package org.kodejava.lang.reflect;

import java.lang.reflect.Method;

public class GetMethods {
    public static void main(String[] args) {
        GetMethods object = new GetMethods();
        Class<? extends GetMethods> clazz = object.getClass();

        // Get all declared methods including public, protected, private and
        // package (default) access but excluding the inherited methods.
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println("Method name        = " + method.getName());
            System.out.println("Method return type = " + method.getReturnType().getName());

            Class<?>[] paramTypes = method.getParameterTypes();
            for (Class<?> c : paramTypes) {
                System.out.println("Param type         = " + c.getName());
            }

            System.out.println("----------------------------------------");
        }

        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");

        // Get all methods including the inherited method. Using the getMethods()
        // we can only access public methods.
        methods = clazz.getMethods();
        for (Method method : methods) {
            System.out.println("Method name        = " + method.getName());
            System.out.println("Method return type = " + method.getReturnType().getName());

            Class<?>[] paramTypes = method.getParameterTypes();
            for (Class<?> c : paramTypes) {
                System.out.println("Param type         = " + c.getName());
            }

            System.out.println("----------------------------------------");
        }

        try {
            // We can also get method by their name and parameter types, here we
            // are trying to get the add(int, int) method.
            Method method = clazz.getMethod("add", int.class, int.class);
            System.out.println("Method name: " + method.getName());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    public int add(int numberA, int numberB) {
        return numberA + numberB;
    }

    protected int multiply(int numberA, int numberB) {
        return numberA * numberB;
    }

    private double div(int numberA, int numberB) {
        return numberA / numberB;
    }
}