This question already has an answer here:
I'm doing some error handling on objects that could be any type, and I want to have special handling for arrays. What I can't figure out is how to get the length of the array regardless of whether it's an array of primitives or Objects. Here's what I mean:
public void checkMyValue(Object valueToCheck) {
// ... null checking, other type checking, etc. Then...
if (valueToCheck.getClass().isArray()) {
// This will throw a ClassCastException for primitive arrays
int length = ((Object[]) valueToCheck).length;
if (length == 0) {
throw new IllegalArgumentException("Empty arrays are not allowed");
}
}
}
Is there any way to get the length of a primitive array without explicitly checking each primitive type?
Aucun commentaire:
Enregistrer un commentaire