Reflection Sample - Whats wrong in this?
Please find the below code.
public class FiledRef {
public static void main(String[] args) {
try{
Class clas = null;
clas = Class.forName("fieldRef.TwoString");
System.out.println("VALUE IS -> "+incrementField("val02",clas));
}catch(Exception ex){
ex.printStackTrace();
}
}
public static int incrementField(String name, Object obj) throws Exception{
Field field = obj.getClass().getDeclaredField(name);
int value = field.getInt(obj) + 1;
field.setInt(obj, value);
return value;
}
}
I have another class TwoString, which contains an int variable val02, which has a value 10.
When I tried the above code for Reflection, I got the compilation Error as java.lang.NoSuchFieldException: val02. Canb you please tell me where I have gone wrong? Can anyone help me to sort it out.....?
As always, I am a bit short with my answer, but I want to add something: If "val02" refers to a static variable of your TwoString, you must not get declared fields from obj.getClass() but pass in the class and get the class's fields. In your case, obj.getClass() will return Class.
> As always, I am a bit short with my answer, but I
> want to add something: If "val02" refers to a static
> variable of your TwoString, you must not get declared
> fields from obj.getClass() but pass in the class and
> get the class's fields. In your case, obj.getClass()
> will return Class.
Huh? You always query a class object for fields, regardless of whether the field is static or not. If you're reflectively invoking a static member, you pass in null in place of the object upon which to invoke
> Huh? You always query a class object for fields,
> regardless of whether the field is static or not. If
> you're reflectively invoking a static member, you
> pass in null in place of the object upon which to
> invoke
Sure. But you shouldn't call getDeclaredMethod() on obj.getClass() if obj is the class already (as it is passed to incrementField() in the OP).
Maybe my comment is too confusing and missing the OP's goal, which does not state, whether it is an instance variable or a class variable (for the latter you would not need an instance of TwoString, that's all I wanted to state).
So let's assume it's an instance variable. In this case, necessitating an instance of TwoString is correct.