Reputation: 7317
This is the exact opposite of how can I remove generic type from class using refactoring.
I want to introduce a type parameter to an interface. It is used quite extensively, so not very practical to do by hand. It is also widely used in import statements and JavaDoc, so a simple global string replace will not work very well either.
Edit:
I did try the "use parent type when possible" refactoring, but it understandably did not work very well at introducing type parameters.
Upvotes: 1
Views: 299
Reputation: 81074
In IntelliJ, you can use the "Change Signature" refactoring. Given this code:
public static void main(String[] args) {
MyContainer container = new MyContainer("hello!");
String val = container.get();
System.out.println(val);
}
class MyContainer {
final Object value;
MyContainer(Object value) {
this.value = value;
}
Object get() {
return value;
}
}
I right-clicked on MyContainer
, then chose Refactor->Change Signature... From here, you can introduce a type parameter T
. You need to give a default concrete type for T
. Most of the time, to preserve existing code, this would be Object
; but it depends on the class you're changing. For example, if MyContainer
above used Number
instead of Object
, the equivalent of the new erasure type would be Number
. But you would also need to declare T extends Number
in that case.
When I finish this, I get the following:
public static void main(String[] args) {
MyContainer<Object> container = new MyContainer<Object>("hello!");
String val = (String) container.get();
System.out.println(val);
}
class MyContainer<T> {
final Object value;
MyContainer(Object value) {
this.value = value;
}
Object get() {
return value;
}
}
Now you can start to use T
in MyContainer
, and by looking at the files that IntelliJ
changed, you can start to see where you need to look to start filling in the correct type arguments (since all auto-generated type parameters will be Object
).
Upvotes: 2