I'm developing a new method for TestClass called setList. The method takes a List of String parameter and sets a member variable of TestClass. Assume the list is large, so it's impractical to copy it.
Now a user of my class decides to cast an ArrayList of Integer as an untyped List and passes it to my method. Compiler doesn't complain. At runtime, there isn't any error until the client attempts to retrieve an element from the list.
What's the best practice for my method to protect the class from being corrupted by this user input? I thought of checking if list is empty and then checking type of all elements in list, but that seems hacky. Even more so if the elements are Generics themselves, etc.
@Test
public void test() {
Map<String, Object> map = new HashMap<>();
List input = new ArrayList<>(Arrays.asList(1, 2, 3));
input.add("12345");
map.put("key", input);
TestClass testClass = new TestClass();
testClass.setList((List) map.get("key"));
List<String> list = testClass.getList();
String element = list.get(0);
}
public static class TestClass {
private List<String> list;
public void setList(List<String> list) {
this.list = list;
}
public List<String> getList() {
return list;
}
}