Ethan Brookman
Ethan Brookman

Reputation: 97

Grabbing int from object[][] array Java Reflect

I need to grab a int from a object[][], but have no idea how to do it with reflection.

I used this method to grab it from an object[]

    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;


}

Since this next one is object[][], I don't know how to go about it.

I want to basically be able to do

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

Upvotes: 1

Views: 64

Answers (1)

Alain O&#39;Dea
Alain O&#39;Dea

Reputation: 21716

You can downcast the Object to Object[][] like this:

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

Or do that inside 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;
}

And leave your callsite as you desired:

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

A few of my opinions on clean code (take or leave of course):

  1. Prefer throw new RuntimeException(e); to e.printStackTrace(); (alter the IDE template)
  2. Prefer explicit code to reflection. Reflection loses type safety.
  3. Prefer specific types to Object

Upvotes: 1

Related Questions