๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

Field class in Reflection API  


Introduction
  • Field class in Java is part of the Reflection API and represents a single field (variable) of a class.
  • It is present in the java.lang.reflect package.
  • The Field class allows you to get information about, and manipulate, fields of objects at runtime.
  • It provides methods to get metadata about a field, such as its name, type, modifiers, and also allows getting and setting field values dynamically.
  • Field class inherits the Member interface:
    Field Class in Java Reflection

Important Methods of Field Class
  • Below are some important methods of Field class:-
  • S.No Method Use
    1 getName() Returns the name of the field.
    2 getType() Returns the data type (Class object) of the field.
    3 getModifiers() Returns the Java language modifiers (public, private, static, etc.) as an int.
    4 get(Object obj) Returns the value of the field for the given object instance.
    5 set(Object obj, Object value) Sets the value of the field for the given object instance.
    6 isSynthetic() Checks if the field is compiler-generated (synthetic).
  • Program:
    import java.lang.reflect.*;
    
    class Student
    {
        public String name;
        private int age;
    
        public Student() {}
    }
    
    public class MainApp
    {
        public static void main(String[] args) throws Exception
        {
            Student s = new Student();
            Class<?> c = Student.class;
    
            // Get declared fields
            for (Field field : c.getDeclaredFields())
            {
                System.out.println("\nField Name: " + field.getName());
                System.out.println("Type: " + field.getType().getSimpleName());
                System.out.println("Modifiers: " + Modifier.toString(field.getModifiers()));
                System.out.println("Is Synthetic: " + field.isSynthetic());
    
                // Access private fields
                field.setAccessible(true);
    
                // Set value dynamically
                if (field.getType() == String.class) field.set(s, "John");
                else if (field.getType() == int.class) field.set(s, 25);
    
                // Get value dynamically
                System.out.println("Value: " + field.get(s));
            }
        }
    }