2

In JavaPoet I can get a TypeName from every Class like this as an example for the List class.

TypeName TYPE_LIST = ClassName.get(List.class);

But how can I check now if a given TypeName is an instance of a List? Let's say I have a method which returns a List<String>. I can get the return type by using:

TypeName returnTyoe = TypeName.get(method.getReturnType());

How can I check if tis method reurns a List? I do not care if it is a List<String> I only want to know if it is at least a List and ignore the generic parameter completely.

Cilenco
  • 6,264
  • 15
  • 62
  • 128

3 Answers3

2

Found an even better way. For everyone also struggling with that use below code:

TypeName TYPE_LIST = ClassName.get(List.class);
boolean isList = isFromType(type, TYPE_LIST)

public static boolean isFromType(TypeName requestType, TypeName expectedType) {
    if(requestType instanceof ParameterizedTypeName) {
        TypeName typeName = ((ParameterizedTypeName) requestType).rawType;
        return (typeName.equals(expectedType));
    }

    return false;
}
Cilenco
  • 6,264
  • 15
  • 62
  • 128
0

As you have pointed out correctly, you won't be able to get whether it's a List<String> because of the type erasure.

If you simply want to check whether it's a List or not then you can do,

return method.getReturnType().contains("java.util.List");
Cilenco
  • 6,264
  • 15
  • 62
  • 128
user2004685
  • 8,721
  • 4
  • 29
  • 49
-1

This was my solution to this problem(Very simple):

 public static boolean isParameterizedType(Class clazz) {
        String simpleName = clazz.getSimpleName();
        return parameterizedTypeSet.contains(simpleName);
    }

private static Set<String> parameterizedTypeSet = new HashSet<>();

    static {
        parameterizedTypeSet.add("List");
    }
Sam Orozco
  • 1,120
  • 11
  • 22
  • This code has no mention of `ClassName` and thus cannot possibly answer the question. Determining whether it is parameterized is also not the same as determining whether it is a `List`. – Matthew Read Nov 22 '20 at 01:26