Search code examples
javaspring-bootcode-generationjavapoet

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,


Solution

  • 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 .