Check if a field is an array type in Java
Description
The following code shows how to check if a field is an array type.
Example
// ww w . j av a2 s . c o m
import java.lang.reflect.Field;
public class Main {
public static void main(String[] args) {
KeyPad target = new KeyPad();
printArrayNames(target);
}
static void printArrayNames(Object target) {
Class targetClass = target.getClass();
Field[] publicFields = targetClass.getFields();
for (int i = 0; i < publicFields.length; i++) {
String fieldName = publicFields[i].getName();
Class typeClass = publicFields[i].getType();
String fieldType = typeClass.getName();
if (typeClass.isArray()) {
System.out.println("Name: " + fieldName + ", Type: " + fieldType);
}
}
}
}
class KeyPad {
public boolean alive;
public int[] codes;
public boolean[] states;
}
The code above generates the following result.