更新时间:2024-04-12 GMT+08:00
分享

移动实例方法

如果此方法在项目中具有类型参数,则此重构允许您将实例(非静态)方法移动到其他类。

执行重构

  1. 在代码编辑器中,将光标放在要移动到另一个类的实例方法的声明上。
  2. 在主菜单或编辑器上下文菜单中,选择Refactor>Move Instance Method

    如果该方法在项目中没有类型参数,则需要将其设置为静态,然后将其移动到所需的类。有关详细信息,请参见使方法静态移动静态成员

  3. 在打开的Move Instance Method对话框中,提供重构选项。

    • Select an instance expression列表中,选择要将实例方法移动到的目标类。潜在移动目标的列表包括当前类中的方法参数的类和字段的类。
    • 为将要移动的方法添加参数名称,并将替换对当前类所有参数的引用。
    • Visibility区域中,指定移动方法的可见性修改器,或选择Escalate 以自动将可见性设置为所需的级别。

  4. 单击Refactor以应用重构。

示例

例如,让我们将实例方法getNameCar类移动到MoveInstanceMethod类方法。

重构前

public class MoveInstanceMethod {
    public static void main(String[] args) throws Exception {
        Car c = new Car();
        System.out.println(c.getName(new MoveInstanceMethod()));
    }
}

class Car {
    String name = "Default Car";

    String getName(MoveInstanceMethod anotherObject) {
        System.out.print(anotherObject.toString());
        return this.name;
    }
}

重构后

public class MoveInstanceMethod {
    public static void main(String[] args) throws Exception {
        Car c = new Car();
        System.out.println(new MoveInstanceMethod().getName(c));
    }

    String getName(Car car) {
        System.out.print(toString());
        return car.name;
    }
}

class Car {
    String name = "Default Car";
}
分享:

    相关文档

    相关产品