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) {


The output of the code snippet:

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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.