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;
    }
}