Close

Java Reflection - Field.getBoolean() Examples

Java Reflection Java Java API 


Class:

java.lang.reflect.Field

java.lang.Objectjava.lang.Objectjava.lang.reflect.AccessibleObjectjava.lang.reflect.AccessibleObjectjava.lang.reflect.AnnotatedElementAnnotatedElementjava.lang.reflect.Fieldjava.lang.reflect.Fieldjava.lang.reflect.MemberMemberLogicBig

Method:

public boolean getBoolean(Object obj)
                   throws IllegalArgumentException,
                          IllegalAccessException

Gets the value of a static or instance boolean field. The provided 'obj' is the object to extract the boolean value from (should be null for static fields).



Examples


package com.logicbig.example.field;

import java.lang.reflect.Field;

public class GetBooleanExample {
private boolean aBool = true;

public static void main(String... args) throws NoSuchFieldException, IllegalAccessException {
Field field = GetBooleanExample.class.getDeclaredField("aBool");
boolean b = field.getBoolean(new GetBooleanExample());
System.out.println(b);
}
}

Output

true




Attempting to get wrong type:

package com.logicbig.example.field;

import java.lang.reflect.Field;

public class GetBooleanExample2 {
private Object aBool;

public static void main(String... args) throws NoSuchFieldException, IllegalAccessException {
Field field = GetBooleanExample2.class.getDeclaredField("aBool");
boolean b = field.getBoolean(new GetBooleanExample2());
System.out.println(b);
}
}

Output

Caused by: java.lang.IllegalArgumentException: Attempt to get java.lang.Object field "com.logicbig.example.field.GetBooleanExample2.aBool" with illegal data type conversion to boolean
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.newGetIllegalArgumentException(UnsafeFieldAccessorImpl.java:69)
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.newGetBooleanIllegalArgumentException(UnsafeFieldAccessorImpl.java:116)
at java.base/jdk.internal.reflect.UnsafeObjectFieldAccessorImpl.getBoolean(UnsafeObjectFieldAccessorImpl.java:41)
at java.base/java.lang.reflect.Field.getBoolean(Field.java:452)
at com.logicbig.example.field.GetBooleanExample2.main(GetBooleanExample2.java:16)
... 6 more




For static field:

package com.logicbig.example.field;

import java.lang.reflect.Field;

public class GetBooleanExample3 {
private static boolean aBool = true;

public static void main(String... args) throws NoSuchFieldException, IllegalAccessException {
Field field = GetBooleanExample3.class.getDeclaredField("aBool");
boolean b = field.getBoolean(null);
System.out.println(b);
}
}

Output

true




See Also