mowienay
mowienay

Reputation: 1354

Generating setter for a created Object in the main Class in INTELLIJ IDEA IDE

Can I generate a setter for an object created in the main class

  1. Created class X
  2. class X has dozens of variables with there setter and getter methods (No problem)
  3. Crated object y from class X in another class
  4. I want to set the variables of object y within the other class

Does intelliJ IDE have a generator for setters to be y.set1() .. y.setn() instead of writing them down tens of times.

Upvotes: 2

Views: 2077

Answers (3)

Bruce
Bruce

Reputation: 21

There is a plugin for that. GenerateAllSetter

To install the plugin, go to:

  • Preferences -> Plugins -> Browse Repositories...
  • Search for: GenerateAllSetter and click in the Install button. Example
  • Restart Intellij.

Usage:

  • Just click the variable you want to generate the setters and then Alt + Enter. There will be an option to "generate all setter": Example
  • After clicking the "generate all setter" option, all setter of a created Object will be generated: Example

Upvotes: -1

Mat
Mat

Reputation: 1389

I was using the constructor trick, but found a better way (to me) :

Go to the "Structure" view for the class you'd like to generate the setters for, and sort members from a to z.

Then you can copy / paste setters

enter image description here

Now with a little bit of multi line editing (alt + left click) you 'll be able to add the missing parts of the line.

enter image description here

Hope that help.

Upvotes: 8

vikingsteve
vikingsteve

Reputation: 40388

No, not directly, however you may want to create a constructor which sets all fields (perhaps messy with dozens of fields, but doable nonetheless...)

  • go into class X, hit Insert to get the Generate popup, hit Enter to select Constructor, then ctrl-A for All, Enter

There is also the possibility to write an Action in a small custom IntelliJ plugin to do this, if you think the effort it is worth the benefit...

Otherwise, if you are dealing with objects with many fields, the Builder design pattern might be worth a look.

Example of Builder pattern

There is an IntelliJ refactoring for this!

Create your constructor using all fields (like above), and from the Refactor menu (right click), choose Replace Constructor With Builder.

Then look for a new class named XBuilder and use it like so...

X y = new XBuilder.setA(1).setB(2).setC(3).createX();

Upvotes: 1

Related Questions