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/