简体   繁体   English

以名称String形式访问Java变量

[英]Access Java variable by its name as a String

I have declared 10 ArrayList s with names arraylist1 , arraylist2 and so on. 我已经声明了10个名为arraylist1arraylist2 ArrayList ,依此类推。

I want to dynamically change variable name in a for loop: 我想在for循环中动态更改变量名称:

for (int i = 1; i < 5; i++)
{
   arraylist + (i).clear();
   //arraylist1.clear();
   //arraylist2.clear();
   //arraylist3.clear();
   //arraylist4.clear();
   //arraylist5.clear();

}

Is it possible? 可能吗? If so what is format to do so? 如果是这样的格式是什么?

You can not address a variable with its name as string (except with reflection, but that's an overkill for this task). 您无法使用其名称作为字符串来处理变量(除了反射,但这对此任务来说太过分了)。

You can add all these ArrayList's to another List. 您可以将所有这些ArrayList添加到另一个List。 This is more flexible and, thus, a better option. 这更灵活,因此是更好的选择。

List<List<ContactDetails>> lists2 = new ArrayList<List<String>>();
for (int i = 0; i < 10; i++) {
    lists2.add(new ArrayList<ContactDetails>());
}

Or add them to an array and access them by array indexes: 或者将它们添加到数组并通过数组索引访问它们:

@SuppressWarnings("unchecked")
List<ContactDetails>[] lists = new List[10];
for (int i = 0; i < lists.length; i ++) {
    lists[i] = new ArrayList<ContactDetails>();
}

Now: 现在:

for (int i = 1; i < 5; i++)
{
   lists[i].clear();
   lists2.get(i).clear();
}

As both List and array are Iterable , you can use the foreach syntax: 由于List和数组都是Iterable ,您可以使用foreach语法:

for (List list : lists)
{
   list.clear();
}

for (List list : lists2) {
    list.clear();
}

If you know how to achieve the same with Lambdas / Stream API, please add to the answer. 如果您知道如何使用Lambdas / Stream API实现相同功能,请添加答案。

如果ArrayList是类属性,则可以使用反射来实现:

((ArrayList) getClass().getField("arraylist" + i).get(this)).clear();

You can also do this with reflection. 你也可以用反射做到这一点。 But I do not recommend it. 但我不推荐它。

public class SoTest {

    @Test
    public void testWithReflection() throws Exception {
        final MyClass myClass = new MyClass();
        for (int i = 0; i < 10; i++) {
            final Field field = myClass.getClass().getDeclaredField("list" + i);
            field.setAccessible(true);
            final List<String> value = (List<String>) field.get(myClass);
            value.clear();
        }
    }

    class MyClass {
        private List<String> list0 = new ArrayList<>();
        private List<String> list1 = new ArrayList<>();
        private List<String> list2 = new ArrayList<>();
        private List<String> list3 = new ArrayList<>();
        private List<String> list4 = new ArrayList<>();
        private List<String> list5 = new ArrayList<>();
        private List<String> list6 = new ArrayList<>();
        private List<String> list7 = new ArrayList<>();
        private List<String> list8 = new ArrayList<>();
        private List<String> list9 = new ArrayList<>();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM