如何使用Java反射遍历对象数组

时间:2018-07-25 12:21:53

标签: java reflection

我想在反射类中遍历Object[]

这是我的课程:

public class Lab  {
    public Browser[] browser;
}

class Browser {
    String url;
}

我想从Lab类的索引3访问browser []并检查url的值

2 个答案:

答案 0 :(得分:2)

您可以使用以下代码段实现该目标:

public boolean urlEquals(Lab lab, String other){
    try{
        Field browsersField = Lab.class.getDeclaredField("browsers");
        Object browsers = browsersField.get(lab);

        Object browser = Array.get(browsers, 3);

        Field urlField = Browser.class.getDeclaredField("url");
        urlField.setAccessible(true);
        Object url = urlField.get(browser);

        return url.equals(other);
    } catch(Exception e){ // probably catch specific exceptions than all
        throw new IllegalStateException(e);
    }
}

答案 1 :(得分:0)

也许以这种方式:

public class Lab
{
public Browser[] browser;
public static void main(String[] args)
{
Lab myLabInstance = new Lab();
myLabInstance.browser = new Browser[] { new Browser(), new Browser(), new Browser(), new Browser(), };
for (Field field : Lab.class.getDeclaredFields())
{
  System.out.println(field.getName());
  if (field.getName().equalsIgnoreCase("browser"))
  {
    field.setAccessible(true);
    Browser[] browsers = (Browser[]) field.get(myLabInstance);
    System.out.println(browsers[3].url.equals("myvalue"));
  }
}}}

class Browser
{
 public String url = "hallo";
}