Can a Field class from Java reflection work on any object? -


i curious if can store instance of field object , use on object pass it. i'm doing ton of reflection work, , recall reading somewhere unsafe store field object , use singleton (more or less) access field class.

is possible, or i'm trying dangerous or flawed in way? made quick test check, , appears work... i'm unsure if test alone proves that.

this assumes we're allowed access field , securityexception won't raised.


code used test:

package test;  import java.lang.reflect.field;  public class testclass {      public static void main(string[] args) {         field fa = null;         field fb = null;          (field f : test.class.getdeclaredfields()) {             switch (f.getname()) {             case "a":                 fa = f;                 break;             case "b":                 fb = f;                 break;             }         }          fa.setaccessible(true);         fb.setaccessible(true);          test ta = new test(5, "test");               test tb = new test(54, "new string");          try {             system.out.println(fa.get(ta) + " " + fa.get(tb) + " " + fb.get(ta) + " " + fb.get(tb));         } catch (illegalargumentexception | illegalaccessexception e) {             e.printstacktrace();         }     } }  @suppresswarnings("unused") class test {      private int a;     private string b;      public test(int a, string b) {         this.a = a;         this.b = b;     } } 

yields:

5 54 test new string 

this fine , it's supposed work way. field refers field in specific class, not specific instance (object) of class - can use instance of class.

ofcourse, if field refers field in class test, can use on objects of type test. illegalargumentexception if try call get(object o) on field passing else test object.

see api documentation of field.get(object o).


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -