Skip to content

Improve UseDiamondOperator suggestion with actual type #727

@Luro02

Description

@Luro02

The current message is a generic one that seems to be difficult to understand:

The types specified in the '< A, B, ... >' can be remove, use '<>' instead.

A better one would be

Explicit type argument String can be replaced with <>

for the code

List<String> value = new ArrayList<String>();

The problem

The check is tricky to implement, hence it is implemented by PMD. There exists an issue #559 for rewriting it in spoon, but is hardly worth the effort (you would have to reimplement java type-inference).

The PMD message only includes the changed type and not the original one: Explicit type arguments can be replaced by a diamond: 'new p.Generic<>()'

The solution

  • It might be possible to resolve the position to its type: RuleViolation#getLocation seems to contain information about not only the line, but also about its column.
  • Resolve it based on the message by finding the referenced type in the source code. E.g. find which spoon element corresponds to new p.Generic<>() and has an explicit type in <>
  • Use the line to infer the type where <> can be simplified. (might not work for multiple simplifications in the same line or source code that spans multiple lines?)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions