Skip to content

[java] SingletonClassReturningNewInstance: False positive due to type cast #5158

Closed

Description

@cowwoc

Affects PMD Version: 7.4.0

Rule: https://docs.pmd-code.org/latest/pmd_rules_java_errorprone.html#singletonclassreturningnewinstance

Description:

Code Sample demonstrating the issue:

public final class ObjectArrayValidatorNoOp 
{
	private static final ObjectArrayValidatorNoOp INSTANCE = new ObjectArrayValidatorNoOp();

	public static <T, E> ObjectArrayValidator<T, E> getInstance()
	{
		@SuppressWarnings("unchecked")
		ObjectArrayValidator<T, E> temp = (ObjectArrayValidator<T, E>) INSTANCE;
		return temp;
	}
}

Expected outcome:

Equivalent output (no error) as when this code is used:

public final class ObjectArrayValidatorNoOp 
{
	private static final ObjectArrayValidatorNoOp INSTANCE = new ObjectArrayValidatorNoOp();

	@SuppressWarnings("unchecked")
	public static <T, E> ObjectArrayValidator<T, E> getInstance()
	{
		return (ObjectArrayValidator<T, E>) INSTANCE;
	}
}

PMD reports a violation at line public static <T, E> ObjectArrayValidator<T, E> getInstance(), but that's wrong. That's a false positive.

Running PMD through: [CLI | Ant | Maven | Gradle | Designer | Other]
Maven plugin 3.24.0

Activity

  1. added
    a:false-positive
    on Aug 3, 2024
  2. changed the title [-][java] SingletonClassReturningNewInstance false positive due to type cast[/-] [+][java] SingletonClassReturningNewInstance: false positive due to type cast[/+] on Oct 23, 2026
  3. added this to the 7.29.0 milestone on Oct 23, 2026
  4. added a commit that references this issue on Oct 23, 2026
  5. added a commit that references this issue on Oct 23, 2026
    05004ef
  6. changed the title [-][java] SingletonClassReturningNewInstance: false positive due to type cast[/-] [+][java] SingletonClassReturningNewInstance: False positive due to type cast[/+] on Oct 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positive

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions