1

I'm trying to write a method which gets an Object and does some logic with the Object's fields.

My method looks like:

public void exampleCast(Object obj) {
    Field[] fields = obj.getClass().getFields();
    for (Field field : fields) {                    
        if (field.getClass().isArray()) {
        
        /*
            HOW CAN I GO OVER THE ARRAY FIELDS , WITHOUT CREATING NEW INSATCNE ?
            SOMETHING LIKE:
            for (int i = 0; i < array.length; i++) {
               array[i] ...
            }
            
        */  
        } else {
            ...
            ...
        }
    }
}   

And an example of objects:

class TBD1 {
    public int x;
    public int y;
    public int[] arrInt = new int[10];
    public byte[] arrByte = new byte[10];
}

And the call to my method:

TBD1 tbd1 = new TBD1();
exampleCast(tbd1);

In my method, I don't know how can I get the array values without create new instance (using the newInstance method) Is it possible? (please see the comment I wrote in my example)

I have read those 2 websites:

... but I didn't get what I wanted to.

1 Answer 1

3

If I understand your question, you might use java.lang.reflect.Array and something like

if (field.getType().isArray()) { // <-- should be getType(), thx @Pshemo
    Object array = field.get(obj);
    int len = Array.getLength(array);
    for (int i = 0; i < len; i++) {
        Object v = Array.get(array, i);
        System.out.println(v);
    }
} // ...
Sign up to request clarification or add additional context in comments.

1 Comment

Shouldn't it be getType instead of getClass? If I am not mistaken getClass invoked on Field instance will return us Field.class which is definitely not an array. What we want to do is check if type of variable is array.

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.