确定通用类型字段的类类型 [英] Determine class type of Generic typed field

查看:66
本文介绍了确定通用类型字段的类类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下代码,我得到了NoSuchFieldException:

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
}

调用方法getCriteriaClass()时出现异常. criteriaType没有任何getter和seeter方法.同样,该字段未初始化.这就是为什么我不能调用criteriaType.getClass()的原因,因为它正在抛出NullPointerException.

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.

我的目的是确定T的类类型,并且我不想在此MultipleSorting类的构造函数中传递T的类.

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.

我无法理解为什么得到NoSuchFieldException.任何指针对我都会非常有帮助.

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

推荐答案

如果您查看

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

返回一个Field对象,该对象反映此Class对象代表的类或接口的指定公共成员字段.

您需要使用:

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

From the JavaDoc ofgetDeclaredField() :

返回一个Field对象,该对象反映此Class对象表示的类或接口的指定声明字段.

请注意,与getField()不同,getDeclaredField()不会找到继承的字段.

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

这篇关于确定通用类型字段的类类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆