mercredi 29 avril 2015

Java: Accessing private field via reflection ()

Junior in Java; using reflection is possible to access private fields (not asking how, Question 1 and Question 2) Ok.

My questions are related with the nature of this behaviour.

  1. Is there any limitation? Can I access any field of any .class I come across?
  2. During my code, once you set the visibility of a field to lets say "public", is it changed forever or just up to the end of the context (method, if, for...)? Code below
  3. Is it ok for everybody? I mean, Seniors programmers of StackOverflow, is it a security breach?

Code:

private Object foo(Object obj) {
  Field f = obj.getClass().getDeclaredField("field"); 
  f.setAccessible(true);
  return (Object) f.get(obj);
}
private Object goo(Object obj) {
 // IS obj.field accesible in this context?
}





Aucun commentaire:

Enregistrer un commentaire