Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NoSuchFieldException on getClass().getField()

Tags:

java

java.lang.NoSuchFieldException: id

The below line is creating the exception.

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

studyplanCategory is a valid object and has got actual values. Beacuse of this exception the load method and the search function in the LazyLoading DataTable of my JSF webapp is not working.

like image 717
user1281029 Avatar asked Apr 25 '12 12:04

user1281029


People also ask

What is getField in Java?

The getField() method of java Class class returns a field object which represents the public member field of the class or interface represented by this Class object. A string specifying the simple name of the desired field is passed as the parameter.

What is Nosuchfieldexception in Java?

Signals that the class doesn't have a field of a specified name.

How to get field from object in Java?

Field. get(Object obj) method returns the value of the field represented by this Field, on the specified object. The value is automatically wrapped in an object if it has a primitive type.


1 Answers

From the Javadoc for 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.

If the field you are trying to retrieve via:

studyplanCategory.getClass().getField(filterProperty)

is private, then you will get a NoSuchFieldException. For private fields, try this instead:

studyplanCategory.getClass().getDeclaredField(filterProperty)

And to get around potential illegal access exceptions when setting values via a field this way:

Field field = studyplanCategory.getClass().getDeclaredField(filterProperty);
field.setAccessible(true);
field.get(studyplanCategory);
like image 117
Perception Avatar answered Oct 04 '22 22:10

Perception