Build Java classes from template files
I am using an API, which requires lot of getters and setters and then perform the operation. Is开发者_如何学C there any template based generation of Java code, which reads APIs setters/getters and generate code. Also some code is common for all objects. So I want to keep the common code in the template, and generated getter or setter code based on API. Is there any process/tool to do that?
I'd look into the documentation for the IDE are you using to program your code. A good one will have tools built in or available as add-ons for this. For example, if you are using Eclipse, you can make code templates for new classes, snippets where you plug in a few variables to generate a block of code, or generate getters and setters based on your existing class variables.
using a Java IDE. In Eclipse you just select your Field and do a Right Click > Source > Generate Getters and Setters.
Same for constructor, toString method, etc.
What about creating a Template Project? You add the skeleton of your Class with some dummy Fields and Getters/Setters and you just replace the names and delete the extra ones? You will not type, just rename (maybe using refactoring) and delete.
Here is a post on how to Create Your Own Project Template for NetBeans... there must be also for other IDEs. http://blogs.oracle.com/seapegasus/entry/tip_create_your_own_project
Use the lombok library: www.projectlombok.org. You put an annotation @Data
on the class and it writes the getters and setters for you, as well as equals, hashcode, tostring. There are other nice features in the library as well.
EDIT: To expand on this a bit, the getters and setters do not show up in your code anywhere. Lombok generates the getters and setters as bytecode during the compilation process. There is plugins for most IDEs that will make the generated code available in drop-downs/code-completion as soon as you add the annotation to your class.
精彩评论