【问题标题】:ClassCastException with Reflections带反射的 ClassCastException
【发布时间】:2014-12-13 23:58:36
【问题描述】:

我尝试通过反射分析运行时信息。我尝试分析的类有一个 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

谁能帮帮我?

【问题讨论】:

  • 你声明 tmp 是最终的,这意味着你不能改变它。不过,在循环中,您正在尝试更改 tmp.这是不可能的
  • 没有。 Final 意味着我不能更改引用,我在这里没有这样做。如果是这种情况,这将导致编译错误。
  • 在第 3 行 final Object arr = stack.get(null);,null 是错误的。阅读 java 文档。
  • @mike 如果它是静态字段 null 很好。无论如何,如果两个类由两个不同的 ClassLoaders 加载,则可能会引发此异常

标签: java reflection


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 1970-01-01
    • 2011-08-25
    相关资源
    最近更新 更多