简体   繁体   中英

Intellij generate static final fields

in a project I need to create many fields with the same type and access modifier
is there a way in intellij to generate public static final fields?

If you type psf and then hit tab, intelliJ will type public static final for you. unsure if this is what you are after

When you go for Generate (for example using command-N on MacOs), IntelliJ only suggests to generate all kinds of methods for you.

I am not aware of a method to insert (almost) identical variable declarations into one (or multiple) java source files.

My workaround: when I have to declare multiple (almost) identical things, I simply turn to column mode.

In other words: I "column" select 5 or 10 empty rows, and then start typing. When the common part is there, I disable column mode and do the necessary fixes for each line manually.

Type all names on separate lines, select the lines and do a regex replace for the selection.

(\w+)

public static final XYZ $1 = new XYZ("$1");

Being comfortable with regex in editing belongs to a developer's basic tools.

By the way interfaces do not need public static final ; that is implicit.

You can utilize Intellij's File and Code templates . Those are used every time a Java class or another entity is created through a project's context menu. Here is the screenshot with a custom template created.

带有自定义模板的上下文菜单

To make your own choose Edit File Templates... option. You can copy the structure of any template and populate it with your own fields. Syntax is quite transparent—guides can be found here .

Here is an example of a custom template which creates a class with a certain amount of fields of type String and prefix of your choice.

模板创建的屏幕截图

Upon a file creation you will be asked to specify a class and a variable name.

输入对话框

After this a file with the following code will be created in no time.

public class MyClass {

  public static final String myString1 = "";
  public static final String myString2 = "";
  public static final String myString3 = "";
  public static final String myString4 = "";
  public static final String myString5 = "";
  public static final String myString6 = "";
  public static final String myString7 = "";
  public static final String myString8 = "";
  public static final String myString9 = "";
}

The advantage of this approach is that once created, templates can be reused instantly. Besides, they can describe rather complex file structures and will save you a lot of time if you create typical files frequently.

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