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 :

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

What you see when using "Infer Generic Type Arguments"


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