A smart way to use inheritance in JavaPoet
I am trying to build a class this way (using 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 father field can be nothing. I tried using NULL for this, but that gives an exception. Isn't there a sane 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 would be nice. Any advice?
+3
source to share
2 answers
One thing you can do right away to shorten your code is to populate the builder with most of the fields you want in the first place:
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();
}
+3
source to share