从object [] []数组Java Reflect中获取int

时间:2015-11-13 23:13:59

标签: java arrays object reflection

我需要从对象[] []中获取一个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;


}

由于下一个是对象[] [],我不知道该怎么做。

我想基本上能够做到

getInterfaceObject()[arg1][arg2].otherStuff();

1 个答案:

答案 0 :(得分:0)

您可以将对象转发给对象[] [] ,如下所示:

((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();

我对清洁代码的一些看法(当然是带走或离开):

  1. 首选将新的RuntimeException(e); 投放到 e.printStackTrace(); (更改IDE模板)
  2. 首选显式代码进行反思。反射失去了类型安全。
  3. 首选特定类型为对象