1

Most probably I oversee something in this trivial use case. My code iterates over annotated fields in a class and the for every field I'd like to run some code dependent on the type. The simplest is just to set a value:

field.setAccessible(true);
final Class<?> type = field.getType();
if (type.equals(Boolean.class)) {
    field.set(this, Boolean.parseBoolean(property));
} else if (type.equals(Integer.class)) {
    field.set(this, Integer.parseInt(property));
} else if (type.equals(String.class)) {
    field.set(this, property);
} else {
    LOGGER.warn("Cannot parse property -{}{}. Unknown type defined.", option.getOpt(),
            field.getName());
}

However this check:

if (type.equals(Boolean.class))

dosn't work as expected e.g. for a field defined as private boolean isVerbose;. After inspection of type I got the property name as just only "boolean" where the Boolean.class property name was filled with "java.lang.Boolean". These object were different.

What would be the right implementation of this scenario?

Adam Bogdan Boczek
  • 1,720
  • 6
  • 21
  • 34

3 Answers3

4

Take a look at this post: Check type of primitive field

basically you need to check primitive types separately (Boolean.TYPE, Long.TYPE etc)

if (field.getType().equals(Boolean.TYPE) {
  // do something if field is boolean
}
Community
  • 1
  • 1
tonakai
  • 805
  • 1
  • 7
  • 15
0

In Java, boolean and Boolean are two different types: boolean is a primitive data type while Boolean is a class in java.lang.Boolean. In this example, in your class you are using private boolean isVerbose which is not of type java.lang.Boolean. Hence you have to change it to private Boolean isVerbose. Hope this helps !!!!!!

Vladimir Vagaytsev
  • 2,871
  • 9
  • 33
  • 36
Sakalya
  • 568
  • 5
  • 15
0

I believe you are having troubles with the java primitives and the boxing. java.lang.Boolean is a class, where as "boolean" just denotes the primitive type.

It is a difference wether you declare:

private boolean myBool; // this a java primitive
private Boolean myOtherBool; // this is an object

Java automatically converts between those types as needed, but as you are inspecting the type yourself you have to pay attention to this.

The same goes for: - Integer - Long - Short - Byte

I hope I did not forget anything.

Melv_80
  • 222
  • 1
  • 5