Check if java.lang.reflect.Field type is a byte array

java, reflection

Solution

`array instanceof byte[]` checks whether `array` is an object of type `byte[]`. But in your case `array` is not a `byte[]`, it's an object of type `Class` that represents `byte[]`.

You can access a `Class` that represents some type `T` as `T.class`, therefore you need the following check:

if (array == byte[].class) { ... }

Problem

I don't do much of reflection so this question might be obvious. For e.g. I have a class: ``` public class Document { private String someStr; private byte[] contents; //Getters and setters } ``` I am trying to check if the field `contents` is an instance of byte array. What I tried: ``` Class clazz = Document.class; Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (field.getType().isArray()) { Object array = field.getType(); System.out.println(array); } } ``` The output of this code is: `class [B`. I see that byte array is found, but if I do: ``` if (array instanceof byte[]) {...} ``` This condition is never `true`. Why is that? And how to check if the object contains fields which are of type of `byte[]`?

Original source