Determine class type of Generic typed field

旧城冷巷雨未停 提交于 2020-01-25 07:51:05

问题


I am getting NoSuchFieldException for the following piece of code:

public class MultipleSorting<T> extends Observable {
    private SelectItem[] criteria1;
    private SelectItem[] order1;
    private SelectItem[] criteria2;
    private SelectItem[] order2;
    private SelectItem[] criteria3;
    private SelectItem[] order3;

    private T criteriaType;

    private T selectedCriteria1;
    private SortOrder selectedOrder1;
    private T selectedCriteria2;
    private SortOrder selectedOrder2;
    private T selectedCriteria3;
    private SortOrder selectedOrder3;    

    private Boolean[] enabledRows = new Boolean[]{Boolean.TRUE, Boolean.FALSE, Boolean.FALSE};

    private Boolean addButtonVisible1 = Boolean.TRUE;
    private Boolean addButtonVisible2 = Boolean.FALSE;
    private Boolean addButtonVisible3 = Boolean.FALSE;

    public MultipleSorting() {
        super();
    }

    private Class<T> getCriteriaClass() throws NoSuchFieldException {
        Field field = this.getClass().getField("criteriaType");
        field.setAccessible(true);
        return (Class<T>)field.getType();
    }

    public void addOrRemoveRow(ActionEvent event) {
        // other codes
        Method setSelectedCriteriaMethod = getClass().getDeclaredMethod("setSelectedCriteria" + (index + 1), new Class[]{getCriteriaClass()});  
        // other codes
    }

    // getters and setters
}

I am getting the exception when I invoke the method getCriteriaClass(). The criteriaType doesn't have any getter and seeter method. Also this field is not initialized. That is why I cannot call criteriaType.getClass() as it is throwing NullPointerException.

My aim is to determine the class type of T and I don't want to pass the class of T in the constructor of this MultipleSorting class.

I am unable to understand why I am getting NoSuchFieldException. Any pointer would be very helpful to me.


回答1:


If you look at the JavaDoc of getField(), you see the problem:

Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object.

You need to use:

Field field = this.getClass().getDeclaredField("criteriaType");

From the JavaDoc ofgetDeclaredField() :

Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object.

Note that getDeclaredField(), unlike getField(), won't find inherited fields.



来源:https://stackoverflow.com/questions/16881102/determine-class-type-of-generic-typed-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!