Wednesday, October 11, 2006

Power/Weakness (???) of Reflection in Java

Blogging after a loooooooooooooooooong time. :)

I got this question and answer from somebody else and thought of sharing:

public class test{
  private String id;
    public String getId() {
      return id;
    }
}


In this class, how to set value to id?

The answer is "Reflection"

Use the following code:

test obj = new test();
Field myfields[] = test.class.getDeclaredFields();
for (int i = 0; i < myfields.length; ++i) {
  if ("id".equals(myfields[i].getName())) {
    Field f = myfields[i];
    //This is important , otherwise u get a access denied exception
    f.setAccessible(true);
    f.set(obj,"I modified it");
  }
}


Seems like this is a security issue in Java. I read that if we used SecurityManager, this can be avoided. ( Have to learn about SecurityManager :) )

No comments: