Michael Wiles
Michael Wiles

Reputation: 21186

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.

Upvotes: 8

Views: 25106

Answers (2)

Brian
Brian

Reputation: 13573

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"

Upvotes: 8

tuergeist
tuergeist

Reputation: 9391

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

Upvotes: 3

Related Questions