Search code examples
javajavapoet

JavaPoet check if TypeName is instance of List


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.


Solution

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