简体   繁体   中英

Access Java variable by its name as a String

I have declared 10 ArrayList s with names arraylist1 , arraylist2 and so on.

I want to dynamically change variable name in a for loop:

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. 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:

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.

如果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<>();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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