Eclipse template variable for getter and setter

I have a little question. I am trying to create templates for getters for my variables inside Eclipse. What I want to do in my getter method is to check if the variable is null or not. If this value is null, I want to assign it a value. However, the problem is that I need to pass the return value of the method to the return type. I could not handle it. Here is the code I would 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 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 return_type is unknown. Please, help.

Thanks so much for your time.

+4
source share
2 answers

Eclipse does not provide a way to do this in getter / setter code templates (i.e. those that use the Generate Getters and Setters tool). Variables in the Insert Variable list are supported only.

${return_type} is only available for use in regular templates (that is, the type you can use with hot keys to complete the code).

As a possible workaround, you can create a static static factory method to create default objects, avoiding the need for a cast:

 public class MyBean { Integer someInt; Double someDoub; public Integer getSomeInt(){ if (someInt == null) someInt = GeneratorUtil.createAndEvaluate(); return someInt; } public Double getSomeDoub(){ if (someDoub == null) someDoub = GeneratorUtil().createAndEvaluate(); return someDoub; } } public class GeneratorUtil { @SuppressWarnings("unchecked") public static <T> T createAndEvaluate() { return (T) new Generator().evaluate(); } } 

Does your Generator class use some type of reflection to determine what type of object will be created?

+1
source

This will do your job:

  if( ${field} == null){ ${field} = ${field}.getClass().cast( new Generator().evaluate()); } return ${field}; 
+1
source

All Articles