我目前正在使用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
。我该如何做到这一点?
答案 0 :(得分:2)
JavaInterfaceSource#addInterface
重载了String
签名。这意味着您可以通过执行一些聪明的字符串连接来创建泛型类型。它还返回JavaInterfaceSource
的相同实例,在上面的示例中为jpaInterface == repository
,因此操作既不必要又具有误导性。
由于它超载了String
,我们只需添加我们自己想要的泛型(读取:尖括号)。
repository.addInterface(JpaRepository.class.getSimpleName() +
"<" + entityName + ", String>");
它可能不像API的其他部分那样优雅,但它最终会生成正确的对象。
public interface SimpleEntityRepository
extends JpaRepository<SimpleEntity, String> {
}