Java 使用Roaster,如何生成具有特定泛型类型的接口?
我目前正在使用生成接口,但我的接口绑定了泛型类型 以下是我试图首先生成它们的内容:Java 使用Roaster,如何生成具有特定泛型类型的接口?,java,roaster,Java,Roaster,我目前正在使用生成接口,但我的接口绑定了泛型类型 以下是我试图首先生成它们的内容: String entityName = "SimpleEntity"; JavaInterfaceSource repository = Roaster.create(JavaInterfaceSource.class) .setName(entityName + "Repository"); JavaInterfaceSource jpaInterface = repository.addI
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 {
}
公共接口SimpleEntityRepository
延伸
org.springframework.data.jpa.repository.JpaRepository{
}
我真正想要的是将泛型绑定到JpaRepository
。如何实现这一点?被字符串
签名重载。这意味着您可以通过进行一些巧妙的字符串连接来创建泛型类型。它还返回相同的JavaInterfaceSource
实例,这样在上面的示例中,jpaInterface==repository
,因此该操作既不必要,又有误导性
由于它重载了字符串
,我们只需添加我们想要的泛型(读:尖括号)
repository.addInterface(JpaRepository.class.getSimpleName() +
"<" + entityName + ", String>");
repository.addInterface(JpaRepository.class.getSimpleName()+
"");
它可能不像API的其余部分那样优雅,但最终生成了正确的对象
public interface SimpleEntityRepository
extends JpaRepository<SimpleEntity, String> {
}
公共接口SimpleEntityRepository
扩展JPA假设{
}
Makoto,至于你的赏金,看看代码,它看起来是最容易获得的解决方案。唯一的另一种方法是使用addInterface(JavaInterface type)
方法,但也不支持为泛型参数指定替换:不支持。