Whenever generics are missing from source code in eclipse it suggests I "Infer Generic Type Arguments..."
The problem is that I don't think "Infer Generic Type Arguments..." has ever actually inferred anything. It typically comes up with no suggestions.
What scenarios does it work for? How does it work?
There have been a few cases where it is possible to "infer" something - eclipse still comes up blank.
Type inference represents the Java compiler's ability to look at a method invocation and its corresponding declaration to check and determine the type argument(s). The inference algorithm checks the types of the arguments and, if available, assigned type is returned.
In order to use a generic type we must provide one type argument per type parameter that was declared for the generic type. The type argument list is a comma separated list that is delimited by angle brackets and follows the type name. The result is a so-called parameterized type.
The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type. For static generic methods, the type parameter section must appear before the method's return type.
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 :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With