Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XxX is not recognized as a valid type

Tags:

java

I have this code :

List<NumericConfig> results = null;

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

But I receive this error :

results is not recognized as a valid type

but this code works :

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

Why my first code doesn't work please ?

like image 370
Olivier J. Avatar asked Dec 06 '25 06:12

Olivier J.


1 Answers

Annotations like

@SuppressWarnings("unchecked")

can only be applied to packages, classes, class members (including enum value), or variable declarations. They can't apply to arbitrary statements.

Section 9.7 of the JLS says

Annotations may be used as modifiers in any declaration, whether package (§7.4), class (§8), interface, field (§8.3, §9.3), method (§8.4, §9.4), parameter, constructor (§8.8), or local variable (§14.4).

Since this appears inside a method body, the compiler has ruled out (package,class,member) declarations and so expects a variable declaration after it. Variable declarations start with a type, so it interprets results as a type name and then realizes it's not, and complains about that, before realizing that = query... is not a valid variable name and initializer.


I think

List<NumericConfig> results

should probably be

List<? extends NumericConfig> results

since you probably don't know the exact implementation type used by the query, and can't validly add to a result list anyway.


I wouldn't add the annotation to the whole method because that might suppress other unchecked assignments that you (or a later code maintainer) are not sure are safe.

You can split the assignment in two

// 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;

or, per my preference, you can attach the annotation to a static method

results = unpackResultList(query, NumericConfig.class);

and elsewhere

@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;
}

This latter option has the benefit of also working on Java 5.

like image 95
Mike Samuel Avatar answered Dec 08 '25 18:12

Mike Samuel