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

I do not think much, so this question may be obvious. 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 contents field is an instance of a 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 an array of bytes is found, but if I do:

 if (array instanceof byte[]) {...} 

This condition is never true . Why is this? And how to check if an object contains fields of type byte[] ?

+7
source share
5 answers

array instanceof byte[] checks to see if array object of type byte[] . But in your case, array not byte[] , it is an object of type Class , which represents byte[] .

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

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

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

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

 if(field.getType() == byte[].class) 
+7
source

Try the following:

 Class<?> cls = field.getType(); if (cls.isAssignableFrom(byte[].class)) { System.out.println("It a byte array"); } 
+3
source

See this helpful tutorial from Oracle.

Array types can be identified by calling the .isArray () class

+1
source

If you try:

 Class<?> array = field.getType(); System.out.println(array.getCanonicalName()); 

he prints byte[] . But the best answer is @axtavt.

0
source

All Articles