NoSuchFieldException when field exists

According to the javadoc, Class.getField() "Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object". Use getDeclaredField() if you want to access non-public fields.


The getField method will only find the field if it's public. You will need to use the getDeclaredField method instead, which will find any field that is declared directly on the class, even if it's not public.


Best solutions for getClass().getField() problem are:

  1. Use getDeclaredField() instead of getField():
        String propertyName = "test";
        Class.forName(this.getClass().getName()).getDeclaredField(propertyName);
  1. Replace "HelloWorld" with your class name:
        String propertyName = "name";
        HelloWorld.class.getDeclaredField(propertyName);

If you want to get the annotation length of the column:

HelloWorld.class.getDeclaredField(propertyName).getAnnotation(Column.class).length();