dimanche 24 mai 2020

I am trying to access a private member variable through reflection but getting java.lang.NoSuchFieldException

''' public class AccessPrivateMember { private String privateName;

public AccessPrivateMember(String privateName) {`enter code here`
    super();
    this.privateName = privateName;
}

public String getPrivateName() {
    return privateName;
}

public void setPrivateName(String privateName) {
    this.privateName = privateName;
}
public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {

    AccessPrivateMember objAccessPrivateMember = new AccessPrivateMember("Secret Name");
    /*
     * Field reflectionAPIField=
     * objAccessPrivateMember.getClass().getDeclaredField("privateName"); String
     * secretName = (String) reflectionAPIField.get(objAccessPrivateMember);
     * System.out.println("secretName="+secretName);
     */
    Field reflectionAPIField2= AccessPrivateMember.class.getClass().getDeclaredField("privateName");
    reflectionAPIField2.setAccessible(true);        
    String secretName2ndWay = (String) reflectionAPIField2.get(objAccessPrivateMember);
    System.out.println("secretName2ndWay="+secretName2ndWay);
}

} '''

    Exception 

    Exception in thread "main" java.lang.NoSuchFieldException: privateName
    at java.lang.Class.getDeclaredField(Unknown Source)
    at io.java.interview.AccessPrivateMember.main(AccessPrivateMember.java:31)
    1. Line Number 31 is 
   Field reflectionAPIField2 = AccessPrivateMember.class.getClass().getDeclaredField("privateName");

2. The code commented is printing the correct result and it is also accessing the private instance variable by privateName. But the line 31 is giving above error.





Aucun commentaire:

Enregistrer un commentaire