Search code examples
javajavapoet

Smart way to use inheritance in JavaPoet


I'm trying to build a class in this way (using the JavaPoet lib):

theClass = TypeSpec.classBuilder(classe.getName())
                                    .addModifiers(javax.lang.model.element.Modifier.valueOf(classe.getProte().toString().toUpperCase()), Modifier.FINAL) //todo
                                    .addMethods(methods)
                                    .superclass(father)
                                    .addFields(fields)
                                    .build();

Where the field "father" can be nothing. I tried using to put NULL inside it, but it gives an exception this way. Isn't there a smart way to write it?

I could write something like

if (father!=null){
   theClass = TypeSpec.classBuilder(classe.getName())
                                .addModifiers(javax.lang.model.element.Modifier.valueOf(classe.getProte().toString().toUpperCase()), Modifier.FINAL) //todo
                                .addMethods(methods)
                                .superclass(father)
                                .addFields(fields)
                                .build();
}
else{
   theClass = TypeSpec.classBuilder(classe.getName())
                                .addModifiers(javax.lang.model.element.Modifier.valueOf(classe.getProte().toString().toUpperCase()), Modifier.FINAL) //todo
                                .addMethods(methods)
                                .addFields(fields)
                                .build();
}

But that wouldn't be nice. Any advice?


Solution

  • One thing you can do immediately to shorten the code is to populate the builder with most of the fields you want first:

    public TypeSpec aNiceMethod(
         ClassModel classe, TypeName father, ArrayList methods, ArrayList fields) {
    
       TypeSpec.Builder theClassBuilder = TypeSpec.classBuilder(classe.getName())
           .addModifiers(
               javax.lang.model.element.Modifier.valueOf(
                   classe.getProte().toString().toUpperCase()),
                   Modifier.FINAL)
           .addMethods(methods)
           .addFields(fields);
       if (father != null) {
            theClassBuilder.superclass(father);
       }
       return theClassBuilder.build();
    }