Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inverse type parameters in Java

I have a class A<X, Y> and I want to refactor it to A<Y, X> in a way that all the references to it would be modified as well.

like image 735
Jacek Kołodziejczyk Avatar asked Jul 25 '11 13:07

Jacek Kołodziejczyk


3 Answers

I don't think that has been implemented in Eclipse yet. It's a rather rare refactoring, though...

But if your type hierarchy below A is not too complex yet, try using this regex-search-replace (where A|B|C means A and all subtypes of A, e.g. B and C):

\b(A|B|C)<\s*(\w+)\s*,\s*(\w+)\s*>

update: since you want to match more sophisticated stuff, try this (without the artifical line-breaks):

\b(A|B|C)<
  \s*((?:\w+|\?)(?:\s+(?:extends|super)\s+(?:\w+|\?))?)\s*,
  \s*((?:\w+|\?)(?:\s+(?:extends|super)\s+(?:\w+|\?))?)\s*>

replace by

$1<$3, $2>

Since you're using Eclipse, you can manually check every replacement for correctness

like image 187
Lukas Eder Avatar answered Oct 26 '22 08:10

Lukas Eder


In Eclipse right-click on the method, then Refactor->Change method signature, you can change the order of the parameters there

like image 44
jasalguero Avatar answered Oct 26 '22 09:10

jasalguero


If you aren't using Eclipse (or another tool that has good refactoring - highly recommended if you're aren't), then I can think of two ways to do this:

First: If you're using TDD, then write a test that will only succeed when the variables are properly swapped. Then make the change to the method signature, and make sure your test passes.

Second: 1. Remove the 2nd parameter from the method signature, which will throw compilation errors on all calls to that method 2. Go to each of the lines that are failing compilation, and carefully swap the variables 3. Put the 2nd variable back into the method signature, in the new, reversed order 4. Run some tests to make sure it still works the way you expect it to

The second method is obviously ugly. But if you're aren't using an IDE with good refactoring support, compilation errors are a good way to capture 100% of the calls to that method (at least within your project). If you're writing a code library that is used by other people, or by other programs, then it becomes much more complicated to communicate that change to all affected parties.

like image 38
jefflunt Avatar answered Oct 26 '22 10:10

jefflunt