Generic Class with JavaPoet
Asked Answered
C

1

11

Hey I'm trying to generate 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 following code:

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

I'm also able to do something like this:

private ResourceListAdapter<? extends ResourceViewHolder> adapter;

With:

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

But I'm not able to combine this. So do you have any ideas??

Califate answered 9/12, 2016 at 16:37 Comment(0)
C
15

I got 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> {}
Califate answered 9/12, 2016 at 18:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.