1

What is the fastest way in Intellij to refactor a java instance method to another class in terms of (refactoring) steps.

For example:

public class Bar {
    public String getX(){
        return "x";
    }
}

public class Foo {
}

public class Runner {
    public static void main(String[] args) {
        new Bar().getX();
    }
}

Refactor to:

public class Bar {
}

public class Foo{
    public String getX(){
        return "x";
    }
}
public class Runner {
    public static void main(String[] args) {
        new Foo().getX();
    }
}
7
  • I don't know for sure about intellij, but I can imagine that is not a refactoring which can be done automatically, or at least in a general-enough way to make it useful: what instance of Foo should the getX method be invoked on? Commented Nov 9, 2015 at 8:14
  • The instance of Foo doesn't matter. new Foo() is fine or if all the instances of Foo in the program are foo the foo would be fine too. Commented Nov 9, 2015 at 8:21
  • Why not just refactor the name of class Bar to Foo (assuming Foo doesn't not exist) Commented Nov 9, 2015 at 8:23
  • Right - it might not matter to you, in this case, but in the general case it would. I can't see a broad-enough use case to warrant making that a built-in refactoring. I'd just get a cup of coffee and start hacking on sed... :( Commented Nov 9, 2015 at 8:24
  • 1
    If the method really is as trivial as it is here (and I'm guessing it's not), you can make Bar.getX() call the static method Foo.getX(), then inline all of the calls to Bar.getX(). Commented Nov 9, 2015 at 8:27

2 Answers 2

1

You can rename class/method/variable with Shift+F6 (just select name and press hotkeys), but You should aware that it don't remove or change already existed name, so you will get a duplicate. The best option remove Foo class before you rename Bar class.

Sign up to request clarification or add additional context in comments.

Comments

1

In IntellJ IDEA 15 you can do:

  1. Position on the method getX();
  2. Press Ctrl/Cmd+F6 (Change Signature)
  3. Add parameter: Type=Foo, name=foo, Default value=new Foo()
  4. Press F6: Move method
  5. Select Foo foo as destination and press Refactor

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.