Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

roaster

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);
jpaInterface.addTypeVariable(entityName);
jpaInterface.addTypeVariable("String");

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

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

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

like image 714
Makoto Avatar asked Oct 30 '22 03:10

Makoto


1 Answers

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, String> {
}
like image 55
Makoto Avatar answered Nov 10 '22 15:11

Makoto