I have a java code and I want to set the fields dynamically using reflection. But I get the NoSuchFieldException error for all the fields despite the fields being present. Surprisingly, I don't get this exception when I try to access all the fields using the getDeclaredFields
method.
import java.lang.reflect.Field;
public class A{
private String firstName;
private String lastName;
private String message;
public static void main(String[] args){
Field[] allFields = A.class.getDeclaredFields(); //This works fine
//Sanity check to verify that the above statement worked correctly
for(Field field:allFields){
System.out.println(field.getName());
}
Field field = A.class.getDeclaredField("firstName"); //Throws the error NoSuchFieldException. This error occurs up for other fields also.
}
}
I don't know why it occurs. I am using Java 7 and IDEA 2016.3.1 community edition.
Aucun commentaire:
Enregistrer un commentaire