开发者

Java Reflection API - Getting the value of a String[] field

开发者 https://www.devze.com 2023-01-19 04:56 出处:网络
I was wondering if it is possible to gra开发者_JAVA百科b a String[] of an unknown size from a class using the java reflection API and store it elsewhere?

I was wondering if it is possible to gra开发者_JAVA百科b a String[] of an unknown size from a class using the java reflection API and store it elsewhere?

Thanks.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消