I have a small question. I’m trying to create templates for getters for my variables inside of Eclipse. What I want to do in my getter method is to check if the variable is null or not. If it is null I want to assign a value to it. However the problem is I need to cast the return value of the method to the getter return type. I couldn’t manage it. Here is the code that I’d like to have:
Integer someInt;
Double someDoub;
Long someLong;
public Integer getSomeInt(){
if(someInt == null) someInt = (Integer) new Generator().evaluate();
return someInt;
}
public Double getSomeDoub(){
if(someDoub == null) someDoub = (Double) new Generator().evaluate();
return someDoub;
}
This is the code that I want to generate.
Here is what I typed as a template:
if( ${field} == null){
${field} = ( ${return_type} ) new Generator().evaluate();
}
return ${field};
As soon as I type this. Eclipse says that return_type is unknown. Please help.
Thank you very much for your time.
Eclipse doesn’t provide a way to do this in getter/setter code templates (i.e., the ones that the “Generate Getters and Setters” tool uses). The variables on the “Insert Variable” list are the only ones supported.
${return_type}is only available for use in regular templates (i.e., the type you might invoke using code completion hotkeys).As a possible workaround, you could create a generified static factory method to produce the default objects, avoiding the need for a cast:
Does your
Generatorclass use some type of reflection to determine what type of object to generate?