1

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();
1
  • 1
    Be aware that if the array is really an Object[][], then it cannot contain an int. You need to retrieve an Integer and extract the wrapped value. Commented Nov 13, 2015 at 23:28

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.