带反射的ClassCastException

时间:2014-12-13 15:00:20

标签: java reflection

我尝试用反射来分析运行时信息。我尝试分析的类有一个me.instrumentor.InstrumentStackElem类型的静态数组,我想使用反射访问和复制它。

代码如下所示:

final Field stack = this.object.getClass().getDeclaredField("ise_array");
stack.setAccessible(true);
final Object arr = stack.get(null);
final InstrumentStackElem[] tmp = new InstrumentStackElem[Array.getLength(arr)];
for (int i = 0; i < tmp.length; i++) {
    tmp[i] = (InstrumentStackElem) Array.get(arr, i);
}

当我尝试运行它时,我在for循环的行中得到java.lang.ClassCastException: me.instrumentor.InstrumentStackElem cannot be cast to me.instrumentor.InstrumentStackElem

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

如果它足以让您处理原始对象,则可以尝试此解决方案。它使您可以使用任意类型,而且您不必担心不同的类加载器。正确实施toString()也会有所帮助,我猜。

import java.lang.reflect.Array;
import java.lang.reflect.Field;

public class Main {

    @SuppressWarnings("unused")
    private static Integer[] targetArray = new Integer[] { 0, 1, 2, 3, 4, 5 };

    public static void main(String[] args) throws Exception {
        Field arrayMember = Main.class.getDeclaredField("targetArray");
        arrayMember.setAccessible(true);

        Object array = arrayMember.get(null);

        int length = Array.getLength(array);

        // get class of array element
        Class<? extends Object> elementType = array.getClass().getComponentType();
        Object copy = Array.newInstance(elementType, length);

        for (int i = 0; i < length; i++) {
            Array.set(copy, i, Array.get(array, i));
        }

        // if you know the type, you can cast
        if (Integer[].class.isInstance(copy)) {
            System.out.println("Integer[].class.isInstance(copy) == true");
            Integer[] copiedArray = Integer[].class.cast(copy);
            for (Integer i : copiedArray)
                System.out.println(i);
        } else {
            for (int i = 0; i < length; i++) {
                System.out.println(Array.get(copy, i));
            }
        }
    }
}

<强>输出

Integer[].class.isInstance(copy) == true
0
1
2
3
4
5
相关问题