JavaPoet的通用类

时间:2016-12-09 16:37:30

标签: java javapoet

嘿我正在尝试生成这样的类:

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

目前我可以生成:

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

使用以下代码:

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

我也可以这样做:

private ResourceListAdapter<? extends ResourceViewHolder> adapter;

使用:

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

但我无法将此结合起来。你有什么想法吗?

1 个答案:

答案 0 :(得分:5)

我有一个解决方案!

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

将生成:

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