Java : Field (reflection) with Examples

Field (Java SE 18 & JDK 18) API Examples.
You will find code examples on most Field methods.


Summary

A Field provides information about, and dynamic access to, a single field of a class or an interface. The reflected field may be a class (static) field or an instance field.

Class diagram

public class AccessTest {
    private int num = 100;
}
final var field = AccessTest.class.getDeclaredField("num");
System.out.println(field); // private int AccessTest.num

final var obj = new AccessTest();

System.out.println(field.canAccess(obj)); // false
//field.getInt(obj); // IllegalAccessException

System.out.println(field.trySetAccessible()); // true
System.out.println(field.canAccess(obj)); // true

System.out.println(field.getInt(obj)); // 100

Fields declared in Member

DECLARED, PUBLIC

Please see the link below.

Methods

boolean equals (Object obj)

Compares this Field against the specified object.

class A {
    int num;
    String str;
}

final var a1 = new A();
final var a2 = new A();

final var num1 = a1.getClass().getDeclaredField("num");
final var num2 = a2.getClass().getDeclaredField("num");

System.out.println(num1.equals(num2)); // true

final var str = a1.getClass().getDeclaredField("str");

System.out.println(str.equals(num1)); // false

Object get (Object obj)

Returns the value of the field represented by this Field, on the specified object.

public class GetTest {
    public int num1 = 100;
    public String str1 = "abcd";

    public static int num2 = 999;
    private String str2 = "XYZ";
}
final var cls = GetTest.class;
final var obj = new GetTest();

final var num1 = cls.getDeclaredField("num1");
System.out.println("num1 : " + num1.get(obj));

final var str1 = cls.getDeclaredField("str1");
System.out.println("str1 : " + str1.get(obj));

final var num2 = cls.getDeclaredField("num2");
System.out.println("num2 : " + num2.get(null));

try {
    final var str2 = cls.getDeclaredField("str2");
    final var ret = str2.get(obj);

} catch (IllegalAccessException e) {
    System.out.println("str2 : IllegalAccessException!");
}

// Result
// ↓
//num1 : 100
//str1 : abcd
//num2 : 999
//str2 : IllegalAccessException!

AnnotatedType getAnnotatedType ()

Returns an AnnotatedType object that represents the use of a type to specify the declared type of the field represented by this Field.

public class Foo {
    public int num;
    public String str;
}
final var cls = Foo.class;

final var numField = cls.getDeclaredField("num");
System.out.println(numField); // public int Foo.num

final var numType = numField.getAnnotatedType();
System.out.println(numType); // int

final var strField = cls.getDeclaredField("str");
System.out.println(strField); // public java.lang.String Foo.str

final var strType = strField.getAnnotatedType();
System.out.println(strType); // java.lang.String

<T extends Annotation> T getAnnotation (Class<T> annotationClass)

Returns this element's annotation for the specified type if such an annotation is present, else null.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Foo {
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Bar {
}

public class A {
    @Foo
    public int num;

    @Bar
    public String str;
}
final var field = A.class.getDeclaredField("num");
System.out.println(field); // public int A.num

final var ret1 = field.getAnnotation(Foo.class);
System.out.println(ret1); // @Foo()

final var ret2 = field.getAnnotation(Bar.class);
System.out.println(ret2); // null
final var field = A.class.getDeclaredField("str");
System.out.println(field); // public java.lang.String A.str

final var ret1 = field.getAnnotation(Foo.class);
System.out.println(ret1); // null

final var ret2 = field.getAnnotation(Bar.class);
System.out.println(ret2); // @Bar()

<T extends Annotation> T[] getAnnotationsByType (Class<T> annotationClass)

Returns annotations that are associated with this element.

@Repeatable(FooArray.class)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Foo {
    String value();
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface FooArray {
    Foo[] value();
}

public class A {
    @Foo("a1")
    @Foo("a2")
    public int num;
}
final var field = A.class.getDeclaredField("num");
System.out.println(field);

System.out.println("-- annotations --");
for (final var a : field.getAnnotationsByType(Foo.class)) {
    System.out.println(a.annotationType().getSimpleName() + " : " + a.value());
}

// Result
// ↓
//public int A.num
//-- annotations --
//Foo : a1
//Foo : a2

boolean getBoolean (Object obj)

Gets the value of a static or instance boolean field.

Please see also : get(Object obj)

public class Foo {
    public boolean value = true;
    public String str = "abcd";
}
final var cls = Foo.class;
final var obj = new Foo();

{
    final var field = cls.getDeclaredField("value");
    System.out.println(field); // public boolean Foo.value

    final var ret = field.getBoolean(obj);
    System.out.println(ret); // true
}
{
    final var field = cls.getDeclaredField("str");
    System.out.println(field); // public java.lang.String Foo.str

    try {
        final var ret = field.getBoolean(obj);
    } catch (IllegalArgumentException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //java.lang.IllegalArgumentException:
    //  Attempt to get java.lang.String field "Foo.str" with illegal data type
    //  conversion to boolean
}

byte getByte (Object obj)

Gets the value of a static or instance byte field.

This method is equivalent except a type to getInt(Object obj).

char getChar (Object obj)

Gets the value of a static or instance field of type char or of another primitive type convertible to type char via a widening conversion.

Please see also : get(Object obj)

public class Foo {
    public char value = 'a';
    public String str = "abcd";
}
final var cls = Foo.class;
final var obj = new Foo();

{
    final var field = cls.getDeclaredField("value");
    System.out.println(field); // public char Foo.value

    final var ret = field.getChar(obj);
    System.out.println(ret); // a
}
{
    final var field = cls.getDeclaredField("str");
    System.out.println(field); // public java.lang.String Foo.str

    try {
        final var ret = field.getChar(obj);
    } catch (IllegalArgumentException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //java.lang.IllegalArgumentException:
    //  Attempt to get java.lang.String field "Foo.str" with illegal data type
    //  conversion to char
}

Class<?> getDeclaringClass ()

Returns the Class object representing the class or interface that declares the field represented by this Field object.

public class AccessTest {
    private int num = 100;
}
final var cls = AccessTest.class;

final var field = cls.getDeclaredField("num");
System.out.println(field); // private int AccessTest.num

final var ret = field.getDeclaringClass();
System.out.println(ret); // class AccessTest
System.out.println(cls.equals(ret)); // true

double getDouble (Object obj)

Gets the value of a static or instance field of type double or of another primitive type convertible to type double via a widening conversion.

Please see also : get(Object obj)

public class Foo {
    public double value = 1.23;
    public String str = "abcd";
}
final var cls = Foo.class;
final var obj = new Foo();

{
    final var field = cls.getDeclaredField("value");
    System.out.println(field); // public double Foo.value

    final var ret = field.getDouble(obj);
    System.out.println(ret); // 1.23
}
{
    final var field = cls.getDeclaredField("str");
    System.out.println(field); // public java.lang.String Foo.str

    try {
        final var ret = field.getDouble(obj);
    } catch (IllegalArgumentException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //java.lang.IllegalArgumentException:
    //  Attempt to get java.lang.String field "Foo.str" with illegal data type
    //  conversion to double
}

float getFloat (Object obj)

Gets the value of a static or instance field of type float or of another primitive type convertible to type float via a widening conversion.

This method is equivalent except a type to getDouble(Object obj).

Type getGenericType ()

Returns a Type object that represents the declared type for the field represented by this Field object.

public class Foo<T> {
    public T value;
    public int num;
}
final var foo = new Foo<String>();

final var field = foo.getClass().getDeclaredField("value");
System.out.println(field); // public java.lang.Object Foo.value

final var ret1 = field.getGenericType();
System.out.println(ret1); // T

final var ret2 = field.getType();
System.out.println(ret2); // class java.lang.Object
final var field = Foo.class.getDeclaredField("num");
System.out.println(field); // public int Foo.num

final var ret1 = field.getGenericType();
System.out.println(ret1); // int

final var ret2 = field.getType();
System.out.println(ret2); // int

int getInt (Object obj)

Gets the value of a static or instance field of type int or of another primitive type convertible to type int via a widening conversion.

Please see also : get(Object obj)

public class Foo {
    public int value = 123;
    public String str = "abcd";
}
final var cls = Foo.class;
final var obj = new Foo();

{
    final var field = cls.getDeclaredField("value");
    System.out.println(field); // public int Foo.value

    final var ret = field.getInt(obj);
    System.out.println(ret); // 123
}
{
    final var field = cls.getDeclaredField("str");
    System.out.println(field); // public java.lang.String Foo.str

    try {
        final var ret = field.getInt(obj);
    } catch (IllegalArgumentException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //java.lang.IllegalArgumentException:
    //  Attempt to get java.lang.String field "Foo.str" with illegal data type
    //  conversion to int
}

long getLong (Object obj)

Gets the value of a static or instance field of type long or of another primitive type convertible to type long via a widening conversion.

This method is equivalent except a type to getInt(Object obj).

int getModifiers ()

Returns the Java language modifiers for the field represented by this Field object, as an integer.

class Foo {
    public int a;
    protected int b;
    private int c;
}

final var cls = Foo.class;

for (final var field : cls.getDeclaredFields()) {
    final var mod = field.getModifiers();
    System.out.println("name = " + field.getName() + " : mod = " + mod);
    System.out.println("  isPublic : " + Modifier.isPublic(mod));
    System.out.println("  isProtected : " + Modifier.isProtected(mod));
    System.out.println("  isPrivate : " + Modifier.isPrivate(mod));
}

// Result
// ↓
//name = a : mod = 1
//  isPublic : true
//  isProtected : false
//  isPrivate : false
//name = b : mod = 4
//  isPublic : false
//  isProtected : true
//  isPrivate : false
//name = c : mod = 2
//  isPublic : false
//  isProtected : false
//  isPrivate : true

String getName ()

Returns the name of the field represented by this Field object.

public class Foo {
    public int num;
    public String str;
}
final var cls = Foo.class;

final var num = cls.getDeclaredField("num");
System.out.println(num); // public int Foo.num
System.out.println(num.getName()); // num

final var str = cls.getDeclaredField("str");
System.out.println(str); // public java.lang.String Foo.str
System.out.println(str.getName()); // str

short getShort (Object obj)

Gets the value of a static or instance field of type short or of another primitive type convertible to type short via a widening conversion.

This method is equivalent except a type to getInt(Object obj).

Class<?> getType ()

Returns a Class object that identifies the declared type for the field represented by this Field object.

Please see getGenericType().

int hashCode ()

Returns a hashcode for this Field.

class Foo {
    int num;
    String str;
}

final var cls = Foo.class;

final var ret1 = cls.getDeclaredField("num").hashCode();
System.out.println(ret1); // -1850314582

final var ret2 = cls.getDeclaredField("str").hashCode();
System.out.println(ret2); // -1850317539

boolean isEnumConstant ()

Returns true if this field represents an element of an enumerated class; returns false otherwise.

enum Foo {
    E1,
    E2,
}

class Bar {
    int num;
}

final var e1 = Foo.class.getDeclaredField("E1");
System.out.println(e1.isEnumConstant()); // true

final var num = Bar.class.getDeclaredField("num");
System.out.println(num.isEnumConstant()); // false

boolean isSynthetic ()

Returns true if this field is a synthetic field; returns false otherwise.

class Foo {
    int num;
}

final var field = Foo.class.getDeclaredField("num");
System.out.println(field.isSynthetic()); // false

void set (Object obj, Object value)

Sets the field represented by this Field object on the specified object argument to the specified new value.

public class SetTest {
    public int num1 = 100;
    public String str1 = "abcd";

    public static int num2 = 999;
    private String str2 = "XYZ";
}
final var cls = SetTest.class;
final var obj = new SetTest();

final var field = cls.getDeclaredField("num1");
System.out.println(field); // public int SetTest.num1

System.out.println(field.getInt(obj)); // 100

field.set(obj, 456);

System.out.println(field.getInt(obj)); // 456
final var cls = SetTest.class;
final var obj = new SetTest();

final var field = cls.getDeclaredField("str1");
System.out.println(field); // public java.lang.String SetTest.str1

System.out.println(field.get(obj)); // abcd

field.set(obj, "defg");

System.out.println(field.get(obj)); // defg
final var cls = SetTest.class;

final var field = cls.getDeclaredField("num2");
System.out.println(field); // public static int SetTest.num2

System.out.println(field.getInt(null)); // 999

field.set(null, 1000);

System.out.println(field.getInt(null)); // 1000
final var cls = SetTest.class;
final var obj = new SetTest();

final var field = cls.getDeclaredField("str2");
System.out.println(field); // private java.lang.String SetTest.str2

System.out.println(field.canAccess(obj)); // false

//field.set(obj, "AAA"); // IllegalAccessException

System.out.println(field.trySetAccessible()); // true
System.out.println(field.canAccess(obj)); // true

System.out.println(field.get(obj)); // XYZ

field.set(obj, "AAA");

System.out.println(field.get(obj)); // AAA

void setAccessible (boolean flag)

Set the accessible flag for this reflected object to the indicated boolean value.

public class AccessTest {
    private int num = 100;
}
final var field = AccessTest.class.getDeclaredField("num");
final var obj = new AccessTest();

System.out.println(field.canAccess(obj)); // false

field.setAccessible(true);
System.out.println(field.canAccess(obj)); // true

field.setAccessible(false);
System.out.println(field.canAccess(obj)); // false

void setBoolean (Object obj, boolean z)

Sets the value of a field as a boolean on the specified object.

Please see also : set(Object obj, Object value)

public class Foo {
    public boolean value = true;
    public String str = "abcd";
}
final var cls = Foo.class;
final var obj = new Foo();

{
    final var field = cls.getDeclaredField("value");
    System.out.println(field); // public boolean Foo.value

    System.out.println(field.getBoolean(obj)); // true

    field.setBoolean(obj, false);

    System.out.println(field.getBoolean(obj)); // false
}
{
    final var field = cls.getDeclaredField("str");
    System.out.println(field); // public java.lang.String Foo.str

    try {
        field.setBoolean(obj, false);
    } catch (IllegalArgumentException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //java.lang.IllegalArgumentException:
    //  Can not set java.lang.String field Foo.str to (boolean)false
}

void setByte (Object obj, byte b)

Sets the value of a field as a byte on the specified object.

This method is equivalent except a type to setInt(Object obj, int i).

void setChar (Object obj, char c)

Sets the value of a field as a char on the specified object.

Please see also : set(Object obj, Object value)

public class Foo {
    public char value = 'a';
    public String str = "abcd";
}
final var cls = Foo.class;
final var obj = new Foo();

{
    final var field = cls.getDeclaredField("value");
    System.out.println(field); // public char Foo.value

    System.out.println(field.getChar(obj)); // a

    field.setChar(obj, 'b');

    System.out.println(field.getChar(obj)); // b
}
{
    final var field = cls.getDeclaredField("str");
    System.out.println(field); // public java.lang.String Foo.str

    try {
        field.setChar(obj, 'b');
    } catch (IllegalArgumentException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //java.lang.IllegalArgumentException:
    //  Can not set java.lang.String field Foo.str to (char)b
}

void setDouble (Object obj, double d)

Sets the value of a field as a double on the specified object.

Please see also : set(Object obj, Object value)

public class Foo {
    public double value = 1.23;
    public String str = "abcd";
}
final var cls = Foo.class;
final var obj = new Foo();

{
    final var field = cls.getDeclaredField("value");
    System.out.println(field); // public double Foo.value

    System.out.println(field.getDouble(obj)); // 1.23

    field.setDouble(obj, 4.56);

    System.out.println(field.getDouble(obj)); // 4.56
}
{
    final var field = cls.getDeclaredField("str");
    System.out.println(field); // public java.lang.String Foo.str

    try {
        field.setDouble(obj, 4.56);
    } catch (IllegalArgumentException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //java.lang.IllegalArgumentException:
    //  Can not set java.lang.String field Foo.str to (double)4.56
}

void setFloat (Object obj, float f)

Sets the value of a field as a float on the specified object.

This method is equivalent except a type to setDouble(Object obj, double d).

void setInt (Object obj, int i)

Sets the value of a field as an int on the specified object.

Please see also : set(Object obj, Object value)

public class Foo {
    public int value = 123;
    public String str = "abcd";
}
final var cls = Foo.class;
final var obj = new Foo();

{
    final var field = cls.getDeclaredField("value");
    System.out.println(field); // public int Foo.value

    System.out.println(field.getInt(obj)); // 123

    field.setInt(obj, 456);

    System.out.println(field.getInt(obj)); // 456
}
{
    final var field = cls.getDeclaredField("str");
    System.out.println(field); // public java.lang.String Foo.str

    try {
        field.setInt(obj, 456);
    } catch (IllegalArgumentException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //java.lang.IllegalArgumentException:
    //  Can not set java.lang.String field Foo.str to (int)456
}

void setLong (Object obj, long l)

Sets the value of a field as a long on the specified object.

This method is equivalent except a type to setInt(Object obj, int i).

void setShort (Object obj, short s)

Sets the value of a field as a short on the specified object.

This method is equivalent except a type to setInt(Object obj, int i).

String toGenericString ()

Returns a string describing this Field, including its generic type.

public class Foo<T> {
    public T value;
    public int num;
}
final var foo = new Foo<String>();

final var field = foo.getClass().getDeclaredField("value");

final var ret1 = field.toGenericString();
System.out.println(ret1); // public T Foo.value

final var ret2 = field.toString();
System.out.println(ret2); // public java.lang.Object Foo.value
final var field = Foo.class.getDeclaredField("num");

final var ret1 = field.toGenericString();
System.out.println(ret1); // public int Foo.num

final var ret2 = field.toString();
System.out.println(ret2); // public int Foo.num

String toString ()

Returns a string describing this Field.

Please see toGenericString().

Methods declared in AccessibleObject

canAccess, getAnnotations, getDeclaredAnnotation, getDeclaredAnnotations, getDeclaredAnnotationsByType, isAccessible, isAnnotationPresent, setAccessible, trySetAccessible

Please see the link below.


Related posts

To top of page