Java Code Examples for java.util.ArrayList#getClass()

The following examples show how to use java.util.ArrayList#getClass() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ArrayListBaseTest.java    From jdk-source-analysis with Apache License 2.0 6 votes vote down vote up
/**
 * 通过反射查看 {@link ArrayList} 的内部属性
 */
public void xray(ArrayList list) {
    Class clazz = list.getClass();
    try {
        Field elementData = clazz.getDeclaredField("elementData");
        elementData.setAccessible(true);
        Object[] objects = (Object[]) elementData.get(list);
        Field sizeField = clazz.getDeclaredField("size");
        sizeField.setAccessible(true);

        int size = 0;
        for (int i = 0; i < objects.length; i++) {
            if (Objects.nonNull(objects[i])) {
                ++size;
            }
        }
        System.out.println("length = " + objects.length
                + ", size = " + sizeField.get(list)
                + ", arraySize = " + size);
    } catch (Throwable e) {
        e.printStackTrace();
    }
}