Generic class with JavaPoet

Hey, I'm trying to create a class like this:

public abstract class ResourceListAdapter<T extends ResourceViewHolder> extends RecyclerView.Adapter<T> {}

At the moment, I can generate:

public abstract class ResourceListAdapter extends RecyclerView.Adapter<?> {}

With the following code:

TypeSpec type = TypeSpec.classBuilder(thisClass).superclass(ParameterizedTypeName.get(adapterClassName,
            WildcardTypeName.subtypeOf(Object.class)))
            .addModifiers(Modifier.ABSTRACT, Modifier.PUBLIC)
            .build();

I can also do something like this:

private ResourceListAdapter<? extends ResourceViewHolder> adapter;

WITH

ParameterizedTypeName.get(thisClass,WildcardTypeName.subtypeOf(resourceViewHolderClassName));

But I can not combine this. So do you have any ideas?

+4
source share
1 answer

I have a solution!

TypeSpec type = TypeSpec.classBuilder(thisClass)
            .superclass(ParameterizedTypeName.get(adapterClassName, TypeVariableName.get("T")))
            .addTypeVariable( TypeVariableName.get("T", resourceViewHolderClassName))

Will generate:

public abstract class ResourceListAdapter<T extends ResourceViewHolder> extends RecyclerView.Adapter<T> {}
+4
source

Source: https://habr.com/ru/post/1663349/


All Articles