gpt4 book ai didi

java - 确定通用类型字段的类类型

转载 作者:行者123 更新时间:2023-12-01 18:48:01 24 4
gpt4 key购买 nike

我收到以下代码的NoSuchFieldException:

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

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

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

最佳答案

如果你看JavaDoc of getField() ,你看到问题了:

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

您需要使用:

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

来自JavaDoc ofgetDeclaredField() :

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

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

关于java - 确定通用类型字段的类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16881102/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com