开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜