title: I am trying to access a private member variable through reflection but getting java.lang.NoSuchFieldException
body: <pre><code>public class AccessPrivateMember {
      private String privateName;
  
      public AccessPrivateMember(String privateName) {
          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);
      }
  
  }
  </code></pre>
  
  <p>Exception </p>
  
  <pre><code>Exception in thread "main" java.lang.NoSuchFieldException: privateName
      at java.lang.Class.getDeclaredField(Unknown Source)
      at io.java.interview.AccessPrivateMember.main(AccessPrivateMember.java:31)
  </code></pre>
  
  <ol>
  <li><p>Line Number 31 is</p>
  
  <pre><code>Field reflectionAPIField2 = AccessPrivateMember.class.getClass().getDeclaredField("privateName");
  </code></pre></li>
  <li>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.</li>
  </ol>