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[]?
array instanceof byte[]checks whetherarrayis an object of typebyte[]. But in your casearrayis not abyte[], it’s an object of typeClassthat representsbyte[].You can access a
Classthat represents some typeTasT.class, therefore you need the following check: