Skip to content

[java] UnnecessaryImport false positive for multiline @link Javadoc #1639

@rillig-tk

Description

@rillig-tk

Affects PMD Version:

  • 7.0.0
  • 6.*
  • 5.*

Rule: UnnecessaryImport

Description:
When a derived class refers to a type in a {@link Type#method(ImportedType)} Javadoc tag and there is a line break after the @link , the ImportedType is flagged as being unused.

Code Sample demonstrating the issue:

import java.io.File;
import java.io.FileOutputStream;

public class Demo {
    /** {@link
     * FileOutputStream#FileOutputStream(File)} */
    void main() {}
}

Running PMD through: doesn't matter

Suggested fix: In UnusedImportsRule.java, change LINKS_PATTERN to match the following strings:

  • "{@link\nType#method(ImportedType)}"
  • "{@link\n*\tqualified.Type#method(ImportedType)}"

Since this is very similar to #1555 it may be wrong to use regular expressions at all. By using a proper Java comment parser (which must exist somewhere since the Javadoc tool uses it), it should be easier to catch this edge case and probably some more.

Quick and dirty hacks:

  • To match the first test string, replace \\{@link(?:plain)?\\s+ with \\{@link(?:plain)?[\\s*]+, which allows asterisks during line breaks.
  • To match the second test string, replace \\p{Alpha}\\w* with \\p{Alpha}\[\w.]*, which allows qualified type names.

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positivePMD flags a piece of code that is not problematic

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions