mrgenco
mrgenco

Reputation: 348

JavaPOET - only classes have super classes, not INTERFACE

I am trying to generate code for JPA repository below using JavaPOET library but i am getting "only classes have super classes, not INTERFACE" error.

@Repository 
public interface UserRepository extends PagingAndSortingRepository<User, Long> { 
}

Here is the JavaPOET code i tried..

TypeSpec userRepository = TypeSpec.interfaceBuilder("UserRepository")
                .addAnnotation(Repository.class)
                .addModifiers(Modifier.PUBLIC)
                .superclass(ParameterizedTypeName.get(ClassName.get(PagingAndSortingRepository.class),  
                                                      ClassName.get(User.class),
                                                      ClassName.get(Long.class)))
                .build();

Any solution/best practice for generating interface extending a class? Thanks,

Upvotes: 0

Views: 511

Answers (1)

davidxxx
davidxxx

Reputation: 131546

The message is rather clear :

"only classes have super classes, not INTERFACE" error.

TypeSpec.Builder.superclass() indeed allows to specify only classes.
To specify an interface, use TypeSpec.Builder.addSuperinterface().

It would give :

TypeSpec userRepository = TypeSpec.interfaceBuilder("UserRepository")
                .addAnnotation(Repository.class)
                .addModifiers(Modifier.PUBLIC)
                .addSuperinterface(ParameterizedTypeName.get(ClassName.get(PagingAndSortingRepository.class),  
                                                      ClassName.get(User.class),
                                                      ClassName.get(Long.class)))
                .build();

It should generate this code:

@org.springframework.data.repository.Repository
public interface UserRepository extends org.springframework.data.repository.PagingAndSortingRepository<User, java.lang.Long> {
}

You can find complete examples in the unit tests of the JavaPOET project.
See the git .

Upvotes: 1

Related Questions