Makoto Makoto - 6 months ago 37
Java Question

Using Roaster, how can I generate an interface with a specific generic type (or types)?

I'm currently using Roaster to generate interfaces, but my interface has generic types bound to it.

Here's what I was trying to generate them to begin with:
String entityName = "SimpleEntity";

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

JavaInterfaceSource jpaInterface = repository.addInterface(JpaRepository.class);

But the above results in generated code that looks (something) like this:

public interface SimpleEntityRepository<SimpleEntity>
extends {

What I actually want is for the generic to be bound to
. How do I accomplish this?

Answer Source

JavaInterfaceSource#addInterface is overloaded with a String signature. This means that you can create a generic type by doing some clever string concatenation. It also returns the same instance of JavaInterfaceSource, such that in the above example, jpaInterface == repository, so that operation is both unnecessary and misleading.

Since it's overloaded with String, we simply add the generics (read: angle brackets) we want ourselves.

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

It may not be as type-elegant as the rest of the API, but it generates the right object in the end.

public interface SimpleEntityRepository
        extends JpaRepository<SimpleEntity> {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download