我需要从对象[][]中获取一个int,但不知道如何通过反射来做到这一点。
我用这个方法从一个对象中抓取它[]
public static Object getInterfaceObject(String clazz, String field, Object obj, int index) {
try {
Client client = Boot.client;
ClassLoader cl = client.classLoader;
Class<?> c = cl.loadClass(clazz);
Field f = c.getDeclaredField(field);
f.setAccessible(true);
Object arr = f.get(client.getClient());
return (Object) Array.get(arr, index);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
由于下一个是object[][],我不知道该怎么做。
我希望基本上能够做到
getInterfaceObject()[arg1][arg2].otherStuff();
最佳答案
您可以将对象向下转换为对象[][],如下所示:
((Object[][]) getInterfaceObject())[arg1][arg2].otherStuff();
或者在getInterfaceObject中执行此操作:
public static Object[][] getInterfaceObject(String clazz, String field, Object obj, int index) {
try {
Client client = Boot.client;
ClassLoader cl = client.classLoader;
Class<?> c = cl.loadClass(clazz);
Field f = c.getDeclaredField(field);
f.setAccessible(true);
Object arr = f.get(client.getClient());
return (Object[][]) Array.get(arr, index);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
并根据需要保留您的调用站点:
getInterfaceObject()[arg1][arg2].otherStuff();
我对干净代码的一些看法(当然是取舍):
- 优先选择 throw new RuntimeException(e); 到 e.printStackTrace();(更改 IDE 模板)
- 更喜欢显式代码而不是反射。反射失去了类型安全性。
- 优先选择特定类型而不是对象
关于java - 从 object[][] 数组中获取 int Java Reflect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33703231/