Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "Infer Generic Type Arguments..." in Eclipse

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.

like image 822
Michael Wiles Avatar asked Nov 30 '12 08:11

Michael Wiles


People also ask

What is infer generic type arguments?

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.

How do you provide a generic parameterized type?

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.

How do you use generic method?

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.


1 Answers

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 :

  1. automatically infer the type of generic arguments.
  2. remove unnecessary type casting.

What you see when using "Infer Generic Type Arguments"

like image 82
Brian Avatar answered Sep 29 '22 22:09

Brian