Java 带反射的ClassCastException
我尝试用反射分析运行时信息。我试图分析的类有一个类型为Java 带反射的ClassCastException,java,reflection,Java,Reflection,我尝试用反射分析运行时信息。我试图分析的类有一个类型为me.instrumentor.InstrumentStackElem的静态数组,我希望使用反射来访问和复制它 代码如下所示: final Field stack = this.object.getClass().getDeclaredField("ise_array"); stack.setAccessible(true); final Object arr = stack.get(null); final InstrumentStackE
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);
}
final Field stack=this.object.getClass().getDeclaredField(“ise_数组”);
stack.setAccessible(true);
最终对象arr=stack.get(null);
final InstrumentStackElem[]tmp=新InstrumentStackElem[Array.getLength(arr)];
for(int i=0;i
当我尝试运行它时,我在for循环的行中得到java.lang.ClassCastException:me.instrumentor.InstrumentStackElem不能强制转换为me.instrumentor.InstrumentStackElem
有人能帮我吗?如果您可以处理原始对象,可以尝试此解决方案。它使您能够处理任意类型,而且您不必担心不同的类装入器。我想,一个正确实现的
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));
}
}
}
}
您声明tmp为最终版本,这意味着您不能更改它。不过,在循环中,您正在尝试更改tmp。这是不可能的。最后的意思是我不能更改引用,我在这里没有这样做。如果是这种情况,这将导致编译错误。在第3行
final Object arr=stack.get(null)代码>,空值错误。阅读java文档。@mike This?@mike如果它是一个静态字段null就可以了。无论如何,如果两个类由两个不同的类加载器加载,则可能会引发此异常
Integer[].class.isInstance(copy) == true
0
1
2
3
4
5