Reputation: 615
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?
Upvotes: 1
Views: 879
Reputation: 34920
Unfortunately you can not do this using JConditional
because of its implementation. Have a look at the source of the method _elseif
:
public JConditional _elseif(JExpression boolExp) {
return _else()._if(boolExp);
}
As you can see, this method just invoke _else()
and then _if
internally.
Actually _else()
is JBlock
which contains braces
({ ... }
) by default. This property of JBlock
can not be switched off manually because it doesn't contain such setter. braces
could be switched off only through special constructor of JBlock
:
public JBlock(boolean bracesRequired, boolean indentRequired) {
this.bracesRequired = bracesRequired;
this.indentRequired = indentRequired;
}
but you are not able to set you own object to _else
field of JConditional
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 flag bracesRequired
of _else
object to false
.
Upvotes: 1