Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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[]?

like image 311
Paulius Matulionis Avatar asked Oct 22 '12 09:10

Paulius Matulionis


2 Answers

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) { ... }
like image 151
axtavt Avatar answered Sep 23 '22 17:09

axtavt


if the array is a class only instanceof Class will be true..

If you want to check the type of a field you can use

if(field.getType() == byte[].class)
like image 40
Peter Lawrey Avatar answered Sep 23 '22 17:09

Peter Lawrey