Search code examples
javajavapoet

Javapoet: writing the same thing with less line of code (addModifiers)


So, I have this code (using the Javapoet Lib):

if (myBeautifulBoolean) <--------------------------
                            theClass = TypeSpec.classBuilder(classe.getName())
                                    .addModifiers(javax.lang.model.element.Modifier.valueOf(classe.getProte().toString().toUpperCase()),  Modifier.FINAL) <-------------------
                                    .superclass(father==null?ClassName.OBJECT:father)
                                    .addMethods(methods)
                                    .addFields(fields)
                                    .build();
                            else
                                theClass = TypeSpec.classBuilder(classe.getName())
                                        .addModifiers(javax.lang.model.element.Modifier.valueOf(classe.getProte().toString().toUpperCase())) <------------------
                                        .superclass(father==null?ClassName.OBJECT:father)
                                        .addMethods(methods)
                                        .addFields(fields)
                                        .build();

and i want it to become something like:

                                theClass = TypeSpec.classBuilder(classe.getName())
                                    .addModifiers(javax.lang.model.element.Modifier.valueOf(classe.getProte().toString().toUpperCase()),  myBeautifulBoolean?Modifier.FINAL:null) <----------
                                    .superclass(father==null?ClassName.OBJECT:father)
                                    .addMethods(methods)
                                    .addFields(fields)
                                    .build();

Where is the problem? if i write myBeautifulBoolean?Modifier.FINAL:null, I get an exception because the parameters of addmodifiers() cannot be null, and there is nothing like Modifier.NOTFINAL

So, is there a way to tell the code "Ehi, if the boolean is true, add an argument, if not, don't"?


Solution

  • addModifiers takes an array. you could do addModifiers(test ? new Modifier[] { mod, Modifier.FINAL} : new Modifier[] { mod }) you could make this prettier with a helper method

    public static <T> T[] arr(T... array) { return array; }
    
    // later
        .addModifiers(test ? arr(mod, FINAL) : arr(mod))