Ethan Brookman
Ethan Brookman

Reputation: 97

Getting value of int[] via reflection

Okay, so I'm trying to get the value of a int[] via reflection, and it's been going poorly. Here's my code:

What I'm trying to get value of

public int[] blah;

for(Field f : c.getDeclaredFields()) {
    f.setAccessible(true);
    if(f.getName().toLowerCase().contains("blah")) {
       Logger.write("Name: "+f.getName() +" Value:"+Array.get(f, 1));
    }
}

No matter what I do I keep getting "blah is not an array".

Upvotes: 2

Views: 105

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

You are trying to pass a field instead of field value. First, you need to use f.get(someObject) to get the actual array from someObject, and then call Array.get on the resulting object, like this:

if(f.getName().toLowerCase().contains("blah")) {
    Object arr = f.get(id);
    System.out.println("Name: "+f.getName() +" Value:"+Array.get(arr, 1));
}

Demo.

Upvotes: 2

Related Questions