Field
class in Reflection API
java.lang.reflect
package.
Field
class allows you to get information about, and manipulate, fields of objects at runtime.
Field
class inherits the Member
interface: Field
Class
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). |
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));
}
}
}
Field Name: name Type: String Modifiers: public Is Synthetic: false Value: John Field Name: age Type: int Modifiers: private Is Synthetic: false Value: 25
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.