使用Roaster,如何生成具有特定泛型类型(或多种类型)的接口?

时间:2017-08-18 22:02:11

标签: java roaster

我目前正在使用Roaster来生成接口,但我的界面有绑定它的泛型类型。

以下是我尝试从头开始生成它们的内容:

String entityName = "SimpleEntity";

JavaInterfaceSource repository = Roaster.create(JavaInterfaceSource.class)
        .setName(entityName + "Repository");

JavaInterfaceSource jpaInterface = repository.addInterface(JpaRepository.class);
jpaInterface.addTypeVariable(entityName);
jpaInterface.addTypeVariable("String");

但是上面会产生生成的代码看起来像这样的东西:

public interface SimpleEntityRepository<SimpleEntity>
        extends
            org.springframework.data.jpa.repository.JpaRepository {
}

我真正想要的是将通用绑定到JpaRepository。我该如何做到这一点?

1 个答案:

答案 0 :(得分:2)

JavaInterfaceSource#addInterface 重载了String签名。这意味着您可以通过执行一些聪明的字符串连接来创建泛型类型。它还返回JavaInterfaceSource的相同实例,在上面的示例中为jpaInterface == repository,因此操作既不必要又具有误导性。

由于它超载了String,我们只需添加我们自己想要的泛型(读取:尖括号)。

repository.addInterface(JpaRepository.class.getSimpleName() +
                                    "<" + entityName + ", String>");

它可能不像API的其他部分那样优雅,但它最终会生成正确的对象。

public interface SimpleEntityRepository
        extends JpaRepository<SimpleEntity, String> {
}