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

Whenever the generic data is missing in the source code in eclipse, it offers me "Infer Generic Type Arguments ..."

The problem is that I don’t think that β€œInfer Generic Type Arguments ...” ever made a conclusion. Usually he does not offer any suggestions.

In what scenarios does this work? How it works?

There have been several cases where you can β€œdeduce” something - the eclipse still looks empty.

+7
source share
2 answers

From Eclipse Help :

Replaces the types of raw types of typical types with parameterized types after identifying all places where this replacement is possible.
Available: Projects, packages and types
Parameters: "Suppose clone () returns an instance of the receiver type." Well-organized classes generally respect this rule, but if you know that your code violates it, clear the check box.

Leave arguments unlimited in raw (not inferring) source code. If there are no restrictions on the elements, for example. ArrayList a, clear this check box so that Eclipse still provides the substitution parameter, replacing the reference to ArrayList.

You can find an example at the end of the page .

NTN

+3
source

Here is an example showing how to use "Infer Generic Type Arguments" in eclipse:

Declare a generic class first

//GenericFoo.java public class GenericFoo<T> { private T foo; public void setFoo(T foo) { this.foo = foo; } public T getFoo() { return foo; } } 

Then create an instance without specifying a type and do 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 reorganized 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 is the "Infer General Argument Arguments":

  • automatically displays the type of general arguments.
  • remove unnecessary type casting.

What you see when using "Infer Generic Type Arguments"

+8
source

All Articles