[英]how to invoke array-list dynamically?
How to invoke Array-name from IPSUM.java class to updateArticleView method by passing its name simply? 如何通过简单地传递其名称来从IPSUM.java类调用Array-name到updateArticleView方法? eg. 例如。 in highlighted row, i want to achieve this article.setText(Ipsum.LateralPull[0]);
在突出显示的行中,我要实现此article.setText(Ipsum.LateralPull[0]);
dynamically 动态地
updateArticleView method updateArticleView方法
IPSUM.java IPSUM.java
A very simple way to do that is to use a HashMap<String, String[]>
and you can put each array to the map with its current field name as its key: 一种非常简单的方法是使用HashMap<String, String[]>
然后可以将每个数组以其当前字段名称作为键放入地图:
map.put("LateralPull", new String[]{"LateralPaull"});
So you can simply call: 因此,您可以简单地致电:
map.get(name);
But If you don't want to use HashMap for any reason you can use java reflection. 但是,如果出于任何原因不想使用HashMap,则可以使用Java反射。 Here is a sample code: 这是一个示例代码:
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"};
}
}
The output is: Item 1. 输出为:项目1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.