Close

Java Reflection - Array.getLength() Examples

Java Reflection Java Java API 


Class:

java.lang.reflect.Array

java.lang.Objectjava.lang.Objectjava.lang.reflect.Arrayjava.lang.reflect.ArrayLogicBig

Method:

public static int getLength(Object array)
                     throws IllegalArgumentException

Returns the length of the specified array object, as an int .


Examples


package com.logicbig.example.array;

import java.lang.reflect.Array;

public class GetLengthExample {

public static void main(String... args) {
double[] arr = {1, 4, 9};
int length = Array.getLength(arr);
System.out.println(length);
}
}

Output

3




package com.logicbig.example.array;

import java.lang.reflect.Array;

public class GetLengthExample2 {

public static void main(String... args) {
Object o = "";
System.out.println(isEmpty(o));
o = new int[]{};
System.out.println(isEmpty(o));
}

private static boolean isEmpty(Object o) {
if (o == null) {
return true;
}
if (o instanceof String) {
System.out.println("-- string --");
return ((String) o).length() == 0;
}
if (o.getClass().isArray()) {
System.out.println("-- array --");
return Array.getLength(o) == 0;
}
return false;
}

}

Output

-- string --
true
-- array --
true




See Also