如何将局部变量提取到 IntelliJ 中的 class 变量?

How to extract a local variable to a class variable in IntelliJ?

我希望能够将方法中声明的局部变量转换为 class 变量。请看下面的例子。

// This is my class now
public class FOO {
    public getX() {
        String X = "test"
        return X;
    }
}

使用键盘快捷键,变量 X 应转换为 class 变量。最终结果应如下所示:

// This is what my class should look like afterwards
public class FOO {
    String X = "test"
    public getX() {
        return X;
    }
}

有没有办法在 IntelliJ 中做到这一点?

高亮 XCTRL + ALT + F

其他类型的提取用以下字母替换F

  • F = 字段
  • P=参数
  • V = 变量
  • C = 常量(静态字段)
  • M=方法

也可通过

访问

右键单击 > 重构 > 提取

Ctrl + Alt + F 是您正在寻找的重构算法。 重构 -> 提取 -> 字段

您需要使用此重构算法的 "Initialize in field declaration" 设置。

在 Mac 上,执行此操作的快捷方式是 ALT + CMD + F.