java - getClass().getField() 上的 NoSuchFieldException

标签 java

java.lang.NoSuchFieldException: id

下面一行正在创建异常。

String fieldValue =String.valueOf(studyplanCategory.getClass().getField(filterProperty).get(studyplanCategory)); 

studyplanCategory 是一个有效的对象并且有实际值。由于此异常,我的 JSF web 应用程序的 LazyLoading DataTable 中的加载方法和搜索功能无法正常工作。

最佳答案

来自Javadoc对于 Class.getField(...):

Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object. The name parameter is a String specifying the simple name of the desired field. The field to be reflected is determined by the algorithm that follows. Let C be the class represented by this object:

If C declares a public field with the name specified, that is the field to be reflected. If no field was found in step 1 above, this algorithm is applied recursively to each direct superinterface of C. The direct superinterfaces are searched in the order they were declared. If no field was found in steps 1 and 2 above, and C has a superclass S, then this algorithm is invoked recursively upon S. If C has no superclass, then a NoSuchFieldException is thrown. See The Java Language Specification, sections 8.2 and 8.3.

如果您尝试通过以下方式检索字段:

studyplanCategory.getClass().getField(filterProperty)

是私有(private)的,那么你会得到一个NoSuchFieldException。对于私有(private)字段,试试这个:

studyplanCategory.getClass().getDeclaredField(filterProperty)

并以这种方式通过字段设置值时绕过潜在的非法访问异常:

Field field = studyplanCategory.getClass().getDeclaredField(filterProperty);
field.setAccessible(true);
field.get(studyplanCategory);

关于java - getClass().getField() 上的 NoSuchFieldException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10315614/

相关文章:

java - Swing 中展开的 float 复选框

java - 如何使用 bash 脚本将所有 jar 结果打印到文件中

java - 在对话框中动态添加 View

java - 何时初始化 Java EE webapp 中的属性?

java - 获取Java中特定网络接口(interface)的名称

java - 如何检测并删除数组中两个以上的重复项?

java - 无法接收嵌入的 ActiveMQ 统计消息

java - 使用 Hibernate 将实体映射到物化 View

java - 为什么要使用 getter 和 setter/accessor?

java - (初学者) JAVA do...while 循环逻辑坏了?