I'm generating Java source code with JCodeModel and want to get an "if-elseif" block like this:
if (foo){
} else if (bar) {
}
As far as I understand the according code would be something like this (where m is a JMethod):
JConditional cond = m.body()._if(JExpr.direct("foo"));
cond._elseif(JExpr.direct("bar"));
Seems to be straight forward, but the result is this:
if (foo) {
} else {
if (bar) {
}
}
You see the syntactic difference, it's not actually an "elseif". Semantically it's the same, I know, but I need it to be generated as shown before (it's part of educational software). Any way to do this?
Unfortunately you can not do this using
JConditional
because of its implementation. Have a look at the source of the method_elseif
:As you can see, this method just invoke
_else()
and then_if
internally.Actually
_else()
isJBlock
which containsbraces
({ ... }
) by default. This property ofJBlock
can not be switched off manually because it doesn't contain such setter.braces
could be switched off only through special constructor ofJBlock
:but you are not able to set you own object to
_else
field ofJConditional
object outwardly.The only way is copy
JConditional
class implementation and generate your own, which will allow you such code manipulation.UPD: Of course you can always use
Reflection
as workaround for manually switching flagbracesRequired
of_else
object tofalse
.