samedi 28 mars 2015

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

I am curious if I can store an instance of a Field object and use that on any object I pass to it. I'm doing a ton of reflection work, and I recall reading somewhere that it is unsafe to store a Field object and use that as a singleton (more or less) to quickly access the field from the class.


Is this actually possible, or is what I'm trying to do dangerous or flawed in anyway? I made a quick test to check, and it appears to work... but I'm unsure if this test alone actually proves that.


This assumes we're allowed to access the field and a SecurityException won't be raised.




Code used to test:



package test;

import java.lang.reflect.Field;

public class TestClass {

public static void main(String[] args) {
Field fa = null;
Field fb = null;

for (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





Aucun commentaire:

Enregistrer un commentaire