How to use "Infer Generic Type Arguments..." in Eclipse
Here's an example showing how to use "Infer Generic Type Arguments" in eclipse:
First declare a generic class
// GenericFoo.java
public class GenericFoo<T> {
private T foo;
public void setFoo(T foo) {
this.foo = foo;
}
public T getFoo() {
return foo;
}
}
Then instantiate it without specifying the type, and do an unnecessary type casting.
// GenericFooUsage.java before refactoring
public class GenericFooUsage {
public GenericFooUsage() {
GenericFoo foo1 = new GenericFoo<Boolean>();
foo1.setFoo(new Boolean(true));
Boolean b = (Boolean)foo1.getFoo();
}
}
After applying "Infer Generic Type Arguments", the code is refactored as:
// GenericFooUsage.java after refactoring
public class GenericFooUsage {
public GenericFooUsage() {
GenericFoo<Boolean> foo1 = new GenericFoo<Boolean>();
foo1.setFoo(new Boolean(true));
Boolean b = foo1.getFoo();
}
}
So what "Infer Generic Type Arguments" does are :
- automatically infer the type of generic arguments.
- remove unnecessary type casting.
From Eclipse Help:
Replaces raw type occurrences of generic types by parameterized types after identifying all places where this replacement is possible.
Available: Projects, packages, and types
Options: 'Assume clone() returns an instance of the receiver type'. Well-behaved classes generally respect this rule, but if you know that your code violates it, uncheck the box.
Leave unconstrained type arguments raw (rather than inferring ). If there are no constraints on the elements of e.g. ArrayList a, uncheck this box will cause Eclipse to still provide a wildcard parameter, replacing the reference with ArrayList.
You can find an example at the end of the page.
HTH