slugmandrew
slugmandrew

Reputation: 1836

Java: How can I reorder constructor and method arguments quickly in eclipse?

This has been bugging me for a while. I'm really pedantic about how my code is formatted, and the order of my member variables is quite important to me.

If I have some Java code like this:

private ConverterOne converterOne;
private Dao dao;
private ConverterTwo converterTwo;

public MyClass(ConverterOne converterOne, Dao dao, ConverterTwo converterTwo)
{
    // omitted for brevity
}

Is there an eclipse feature or plugin that will easily allow me to change it to this (without cutting and pasting)?:

private ConverterOne converterOne;
private ConverterTwo converterTwo;
private Dao dao;

public MyClass(ConverterOne converterOne, ConverterTwo converterTwo, Dao dao)
{
    // omitted for brevity
}

Ideally I'd like to highlight the constructor argument I want to move and press some command and left/right.

Does this exist, or what alternatives are there?

Upvotes: 2

Views: 1228

Answers (3)

hiergiltdiestfu
hiergiltdiestfu

Reputation: 2357

A solution to your synchronizing needs, but needs manual intervention. All this assumes the field names are always equal to the parameter labels.

We start off with the "wrong order":

private int a;
private int b;
private int c;

public SettingsDialog(int a, int b, int c) {
    ...
}

Now use ALT+UP or ALT+DOWN on the fields to change them to the desired order.

private int a;
private int c;
private int b;

Next, right click on the editor and select Source > Generate Constructor using Fields ..., with your cursor above the "wrong" constructor.

The wizard will show the fields in the sequence they appear in the class so you can just leave it as is (or deselect extraneous fields) and click Finish.

This will give you a new constructor with the "correct" parameter ordering above your old, wrong constructor:

private int a;
private int c;
private int b;

public SettingsDialog(int a, int c, int b) {
    ... //(marker1)
}

public SettingsDialog(int a, int b, int c) { //(marker2)
    ...
}

Now place your cursor on the first line of the body of the new constructor ((marker1)) and delete all lines via CTRL+D until you delete the first line of your old constructor ((marker2)). So you delete the entire new body plus the signature of the old constructor. Now the new signature sits atop the body of the old constructor.

This is a manuel step, but it's pretty straight forward, satisfies your field-ordering constraint and works for arbitrary complex constructor parameter orderings.

Upvotes: 0

Raniz
Raniz

Reputation: 11123

You can select Change Method Signature from the refactor menu or hit ALT + SHIFT + C with the cursor on the method.

This brings up a dialog that will allow you to easily reorder the method arguments.

Upvotes: 2

NickJ
NickJ

Reputation: 9579

Select the method in eclipse, right-click > refactor > change method signature.

Upvotes: 3

Related Questions