2016-03-06 97 views
0

如何从IPSUM.java类调用Array-name到updateArticleView方法通过简单地传递它的名字? 例如。在突出显示的行,我想要实现这个article.setText(Ipsum.LateralPull[0]);动态如何动态调用数组列表?

updateArticleView方法

enter image description here

IPSUM.java

enter image description here

回答

0

一个非常简单的方法来做到这一点是使用HashMap<String, String[]>,你可以把e ACH阵列与当前的字段名称作为其主要的地图:

map.put("LateralPull", new String[]{"LateralPaull"}); 

所以,你可以简单地调用:

map.get(name); 

,但如果你不想使用HashMap中因任何原因,你可以使用Java反射。下面是一个示例代码:

public class Main { 

public static void main(String[] args) { 

    try { 
     Test test = new Test(); 
     Field field = Test.class.getDeclaredField("list"); 
     String[] list = (String[]) field.get(test); 
     System.out.println(list[0]); 
    } catch (NoSuchFieldException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (SecurityException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IllegalArgumentException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IllegalAccessException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    HashMap<String, String[]> map = new HashMap<>(); 
    map.put("hasahn", new String[]{"df"}); 



} 

private static class Test{ 
    String[] list = new String[]{"Item 1"}; 
} 
} 

输出是:项目1.

+0

冷静,现在我会尝试。并让你知道它是否适用于我的应用程序 –