IntelliJ IDEA 2024.2 Help

Convert Raw Types to Generics refactoring

The Convert Raw Types to Generics refactoring is designed to transform existing code that does not use Generics, into the Generics-aware code. The refactoring analyzes existing code, and for each raw type creates safe and consistent parameter type.

Install the Additional Java Refactorings plugin

This functionality relies on the Additional Java Refactorings plugin, which you need to install and enable.

  1. Press Ctrl+Alt+S to open settings and then select Plugins.

  2. Open the Marketplace tab, find the Additional Java Refactorings plugin, and click Install (restart the IDE if prompted).

Run the Convert Raw Types to Generics refactoring

  1. Select the level of code transformation, which can be a method, a class, a package or directory, in the Project or Structure view, or place the caret at the class or method name in the editor. If you want to apply generics to a single code fragment, select one in the editor.

  2. From the main menu or from the context menu, select Refactor | Convert Raw Types to Generics.

  3. In the dialog that opens, define the refactoring options.

    Convert Raw Types to Generics
  4. Preview and apply changes.

Example

IntelliJ IDEA tries to generate code, which is as correct as possible from the Java point of view. In other words, each context introduces some type restrictions, and the refactoring produces the best possible type (in our case <String>) that does not contradict with the existing contexts.

Before

After

public void method() { List list = new LinkedList(); list.add("string"); }
public void method() { List<String> list = new LinkedList<String>(); list.add("string"); }

Convert raw types to generics refactoring

Use this dialog to specify options for the Convert raw types to generics refactoring.

Item

Description

Drop obsolete casts

If this option is checked, IntelliJ IDEA analyzes whether the parameter cast cases are changed by refactoring. If the resulting parameter type is similar to the obsolete one, the cast statement is removed.

Leave Object-parameterized types raw

Check this option to make objects, that have java.lang.Object as a parameter, raw.

Perform exhaustive search

Check this option to perform search in all nodes.

Generify Objects

Check this option to transform the java.lang.Object objects into the type they are actually used for.

Produce wildcard types

Check this option to produce wildcard types where possible (expressions like List<? extends String>).

Preserve raw arrays

If this checkbox is selected, the arrays are not changed to the arrays with parameterized types. Otherwise, the arrays will be transformed to parameterized type.

Clearing this checkbox can be risky and result in uncompilable code.

Last modified: 22 July 2024