2

I am trying to implement program that will create an array out of the fields of a certain class and then access each field

I have the following class:

public class Example {

  public int[] a = {1,2,3};
  public int[] b = {1,1,1};
  public int[] c = {2,2,2};
}

In a different class I want to access all of these fields and place them into the array "testArray"

import java.lang.reflect.Field;
public class Test { 

  Example t = new Example();
  Field[] testArray = t.getClass().getFields();

  for (Field elem: testArray) {
   // access the fields
  }

}

How can I access the fields this way?

NOTE: for some reasone this gives me an error of Syntax error on token ";", { expected after this token

3
  • What is the difference? Don't both methods work? Commented Oct 29, 2014 at 2:52
  • @dasblinkenlight thank you for the small fix, but it still gives me the same error Commented Oct 29, 2014 at 2:55
  • Yeah, apparently they do, must have missed that memo... Commented Oct 29, 2014 at 2:56

2 Answers 2

3

You are almost there: once you got an array of fields, call get on each one, passing the instance of the object from which you wish to get the property (in this case, that would be t):

Object[] fieldsOfT = new Object[testArray.length];
int i = 0;
for (Field f : testArray) {
    fieldsOfT[i++] = f.get(t);
}
for (Object v : fieldsOfT) {
    System.out.println(v);
}

Demo.

Of course this would not print pretty representations of the objects, because int[] arrays do not provide a meaningful toString, but you have the value there as an object, so you can cast it, and print the values as needed.

Sign up to request clarification or add additional context in comments.

Comments

1

You get an error because none of the code lives inside of a method. Move it into a test method.

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.