NoSuchFieldException on getClass (). GetField ()

java.lang.NoSuchFieldException: id

The next line throws an exception.

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

studyplanCategory is a valid object and has actual values. Due to this exception, the load method and search function in the LazyLoading DataTable of my JSF web application do not work.

+5
source share
4 answers

An application throws this exception because it does not see the attributes you want to return. The getField () method returns non-private attributes, so if your attributes are private, the method does not see them. You can check out http://docs.oracle.com/javase/tutorial/reflect/member/fieldTrouble.html

, , , . ( , ) .

public List<Car> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,String> filters) {  
        List<Car> data = new ArrayList<Car>();  

        //filter  
        for(Car car : datasource) {  
            boolean match = true;  

            for(Iterator<String> it = filters.keySet().iterator(); it.hasNext();) {  
                try {  
                    String filterProperty = it.next();  
                    String filterValue = filters.get(filterProperty);  
                    String fieldValue = String.valueOf(car.getClass().getField(filterProperty).get(car));  

...

, , . . bean , . , .

//EDIT: Man , getDeclaredField(), , , IlegalAccessException. , . , .

+7

Javadoc Class.getField(...):

Field, , . - , . . C - , :

C , . 1 , C. , . 1 2 , C S, S. C , NoSuchFieldException. . "Java" , 8.2 8.3.

, , :

studyplanCategory.getClass().getField(filterProperty)

, NoSuchFieldException. :

studyplanCategory.getClass().getDeclaredField(filterProperty)

:

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

getClass().getField():

getDeclaredField() getField()

1)

String propertyName = "test";<br/>
Class.forName(this.getClass().getName()).getDeclaredField(propertyName);

2)

String propertyName = "name";<br/>
Replace **"HelloWorld"** with your class name<br/>
HelloWorld.class.getDeclaredField(propertyName)
+1

. , . ,

  private Object getVariableValue(Object clazz, String variableName) {
    try {
        Field field = clazz.getClass().getField(variableName);
        return field.get(clazz);
    } catch (NoSuchFieldException e) {
        return "";
    } catch (IllegalAccessException e) {
        return "";
    }

}
0

All Articles