gpt4 book ai didi

java - 在java反射中将Field.get()返回的Object转换为String[]

转载 作者:行者123 更新时间:2023-11-30 04:14:18 24 4
gpt4 key购买 nike

我有一个泛型类,它维护一个内部数组(比如数据)和数组中的元素数量(比如 N)(都是私有(private)的)。我可以向数组添加元素,这将更新 N 的值。该类的公共(public) API 没有用于数据数组或 N 的 get 方法。我仍然想编写单元测试来检查数组和 N 的状态。

    public class InternalArray<T> {
private T[] data;
private int N;
private int head;
public InternalArray() {
super();
data = (T[]) new Object[10];
N = 0;
head = 0;
}

public void add(T item){
data[head]=item;
head++;
N++;
}

public T get(){
T item = data[--head];
N--;
return item;
}
}

在这里,我只能测试公共(public)API。但是我需要测试私有(private)变量的内部状态。我以为我可以使用反射访问字段。我尝试了下面的代码,我可以获得 N 的值。当涉及到 T[] 数据时,我不知道如何转换结果 对象String[](来自调用arrayf.get(inst))

public static void demoReflect(){
try {
Class t = Class.forName("InternalArray");
System.out.println("got class="+t.getName());
InternalArray<String> inst = (InternalArray<String>) t.newInstance();
System.out.println("got instance="+inst.toString());

inst.add("A");
inst.add("B");
Field arrayf = t.getDeclaredField("data");
arrayf.setAccessible(true);
Field nf = t.getDeclaredField("N");
nf.setAccessible(true);
System.out.println("got arrayfield="+arrayf.getName());
System.out.println("got int field="+nf.getName());
int nval = nf.getInt(inst);
System.out.println("value of N="+nval);
Object exp = arrayf.get(inst);
//how to convert this to String[] to compare if this is {"A","B"}

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}

这给出了下面的输出

got class=InternalArray
got instance=InternalArray@c2ea3f
got arrayfield=data
got int field=N
value of N=2

最佳答案

通过调用 arrayf.get(inst) 获得的 Object 类型为 Object[],而不是 String[],因为Java泛型是通过type erasure实现的。你可以这样做:

Object[] strings = (Object[])arrayf.get(inst);
System.out.println(strings.length);
for (int i = 0 ; i != strings.length ; i++) {
String s = (String)strings[i];
...
}

附注我将不再讨论对实现的私有(private)细节进行单元测试是否是一个好主意。

关于java - 在java反射中将Field.get()返回的Object转换为String[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18789843/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com