Skip to content

[java] StringToString rule false-positive with field access #2080

Closed
@niktekusho

Description

@niktekusho

Affects PMD Version: 6.18.0

Rule: StringToString

Description:

Attached code should help to understand better the following description.

We found a false-positive case for the rule String.toString().
When you assign an object field (of type String) to a field of another object (not of type String) calling toString(), the rule emits a warning about calling toString on a String object only when the field names match (value = otherObj.value.toString()). If either one of the field name changes, Pmd stops emitting the warning (workaround).

Since the enum is not a String object, we think that the warning is a false-positive triggered by the field name equality.

Code Sample demonstrating the issue:

See attached project for a ready-to-go reproduction case.

public enum AnEnum {

	A,
	B,
	C;

}

public class AnEnumUser {

	private final String value;

	public AnEnumUser(final OtherEnumUser otherUser) {
                // The following line triggers the "false-positive" warning
		value = otherUser.value.toString();
	}

	public String getValue() {
		return value;
	}

}

public class OtherEnumUser {
	public final AnEnum value;

	public OtherEnumUser(final AnEnum value) {
		this.value = value;
	}
}

public final class Main {
	private Main() {
	}

	public static void main(final String[] args) {
		final OtherEnumUser a = new OtherEnumUser(AnEnum.A);
		System.out.println("Original " + a.value);

		final AnEnumUser aCopy = new AnEnumUser(a);
		System.out.println("Copy " + aCopy.getValue());

	}
}

Running PMD through: Gradle

Attached reproduction project (forgive the eclipse files)

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positivePMD flags a piece of code that is not problematicin:symbol-tableAffects the symbol table code

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions