0

I was wondering if it is possible to grab a String[] of an unknown size from a class using the java reflection API and store it elsewhere?

Thanks.

1
  • 1
    Yes, you do it with String[] just like with any other type. Commented Oct 7, 2010 at 4:14

1 Answer 1

4
class Foo {
  private String[] bar;

  public Foo(String[] bar) {
    this.bar = bar;
  }

  public static void main(String[] args) throws Exception {
    Foo foo = new Foo(new String[] {"a", "b", "c"});
    Field barField = Foo.class.getDeclaredField("bar");
    String[] bar = (String[]) barField.get(foo);
    System.out.println(Arrays.toString(bar)); // [a, b, c]
  }
}

In addition to getDeclaredField(String), there's getField(String) and getFields() which only return public fields as well as getDeclaredFields() for all fields a class declares.

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.