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 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) { ... }
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With