1

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

fabien
  • 1,529
  • 1
  • 15
  • 28
  • 1
    See [this question](http://stackoverflow.com/questions/2481862/how-to-limit-setaccessible-to-only-legitimate-uses) for some great discussion on the topic. – Ben Siver Jan 17 '14 at 17:54
  • 1
    Isn't it easier to add an interface/method that modifies the list, and not to rely on a reflection voodoo? – Alexander Pogrebnyak Jan 17 '14 at 18:07
  • According to http://stackoverflow.com/questions/12237565/reflection-why-are-there-methods-like-setaccessible, you would need to configure a `SecurityManager` to do so. – ralfstx Jan 21 '16 at 09:33

0 Answers0