field.setAccessible(true) 是不好的做法吗?

use*_*209 5 java reflection getter annotations private

在 Java 中,我尝试使用反射来迭代声明的字段,这样我就可以获得注释以及字段本身的基础值:

   for(Field field : CustomObject.getClass().getDeclaredFields()) {
       field.setAccessible(true);
       Object value = field.get(CustomObject);
       CustomAnnotation annotation = field.getAnnotation(CustomAnnotation.class);
       if (annotation != null) {
           //do stuff with annotation and object's value for this field
       }
    }
Run Code Online (Sandbox Code Playgroud)

在这种情况下,该字段可能是私有的,这意味着我无法直接访问它,field.get()除非我先将其设置为可访问。

  1. 这是不好的做法吗?尽管它似乎有效,但我忍不住觉得这违反了一些关键的 OOP 原则。

  2. 完成后我必须转向吗setAccessiblefalse

  3. 有没有更好的方法通过调用对象的 getter 来访问对象的底层值?