Problem is simple: I have a class with some private attributes and I want to guarantee that nothing and no one will ever be able to alter these attributes unless I provide methods to do so.
It's been more than an hour I'm looking for a, hopefully simple, answer and I couldn't find anything conclusive so far.
Let see the code:
public final class MyObject {
private List<Integer> list = new ArrayList<Integer>(5);
public MyObject() {
for (int i = 1; i <= 5; i++) {
list.add(i);
}
}
public List<Integer> toList() {
return new ArrayList<>(list);
}
}
Now, I want something like that:
void test() throws Exception {
MyObject mo = new MyObject();
Field f = mo.getClass().getDeclaredField("list");
f.setAccessible(true);
List<Integer> myList = (List<Integer>) f.get(mo);
myList.add(100);
}
to always fail (on the setAccessible(true) call) for all instances of MyObject, in all threads.
I am using reflection and modify some private fields of other classes so I can't just turn that feature off for the entire program.
I am also hoping for something self-contained that I could put in the static initializer of MyObject but if that is not possible, that's fine...