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
JConditionalbecause of its implementation. Have a look at the source of the method_elseif:As you can see, this method just invoke
_else()and then_ifinternally.Actually
_else()isJBlockwhich containsbraces({ ... }) by default. This property ofJBlockcan not be switched off manually because it doesn't contain such setter.bracescould be switched off only through special constructor ofJBlock:but you are not able to set you own object to
_elsefield ofJConditionalobject outwardly.The only way is copy
JConditionalclass implementation and generate your own, which will allow you such code manipulation.UPD: Of course you can always use
Reflectionas workaround for manually switching flagbracesRequiredof_elseobject tofalse.