简体   繁体   中英

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.

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

在此输入图像描述

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

在此输入图像描述

Hope that help.

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();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM