XxX未被识别为有效类型

时间:2013-04-12 16:38:55

标签: java

我有这段代码:

List<NumericConfig> results = null;

@SuppressWarnings("unchecked")
results = query.getResultList(); // query is JPA named query

但是我收到了这个错误:

  

结果未被识别为有效类型

但是此代码有效:

@SuppressWarnings("unchecked")
List<NumericConfig> results = query.getResultList(); // query is JPA named query

为什么我的第一个代码不起作用?

1 个答案:

答案 0 :(得分:4)

注释如

@SuppressWarnings("unchecked")

只能应用于包,类,类成员(包括enum值)或变量声明。它们不能适用于任意陈述。

Section 9.7 of the JLS

  

注释可用作任何声明中的修饰符,无论是包(第7.4节),类(第8节),接口,字段(第8.3节,第9.3节),方法(第8.4节,第9.4节),参数,构造函数( §8.8),或局部变量(§14.4)。

由于它出现在方法体内,因此编译器已经排除了(包,类,成员)声明,因此需要在它之后进行变量声明。变量声明以一个类型开头,因此它将results解释为类型名称,然后在意识到= query...不是有效的变量名和初始化程序之前意识到它并且抱怨它。


我认为

List<NumericConfig> results

应该是

List<? extends NumericConfig> results

因为您可能不知道查询使用的确切实现类型,并且无论如何都无法有效地添加到结果列表中。


我不会将注释添加到整个方法中,因为这可能会抑制您(或后来的代码维护者)不确定安全的其他未经检查的分配。

您可以将作业拆分为两个

// This is type-safe because query is known to be a JPA named query.
// We use ? extends because query may be a more specific concrete type,
// and because we cannot add to the list owned by query.
@SuppressWarnings("unchecked")
List<? extends NumericConfig> resultListTyped = query.getResultList();
results = resultListTyped;

或者,根据我的偏好,您可以将注释附加到静态方法

results = unpackResultList(query, NumericConfig.class);

和其他地方

@SuppressWarnings("unchecked")
private static <T>
List<? extends T> unpackResultList(Query query, Class<T> resultType) {
  List<T> results = query.getResultList();
  // A quick and dirty sanity check of just the first value.
  assert results.isEmpty() || resultType.isInstance(results.get(0));
  return results;
}

后一种选择的好处还在于使用Java 5。

相关问题