Check if java.lang.reflect.Field type is a byte array
Solution 1
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) { ... }
Solution 2
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)
Solution 3
Try this:
Class<?> cls = field.getType();
if (cls.isAssignableFrom(byte[].class)) {
System.out.println("It's a byte array");
}
Solution 4
See this useful tutorial from Oracle
Array types may be identified by invoking Class.isArray()
Related videos on Youtube
Paulius Matulionis
Check some of my posts at: http://pauliusmatulionis.blogspot.co.uk/
Updated on September 16, 2022Comments
-
Paulius Matulionis over 1 year
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 ofbyte[]
?