0

I have this abstract class

public abstract class SomeClass<S> {// S should be equal to the type of the class which extends this class
    private final Validator validator;

    ...

    protected void someMethod() {
        Set<ConstraintViolation<S>> violations =
                                                  validator.validate((S) this); //here I get the warning
}

I am getting a warning about an unchecked cast. I know why there is a warning, but I couldn't figure how to do the required check.

I thought of if(this instanceof S) but this is always true as it will be executed at runtime in the subclass's code and from that context this will refer to the subclass

How can I solve this to get rid of the warning (without suppressing the warning) and enforce the subclass to put its type in the generic upon declaration (I don't want the scenario which happens in this answer)

HHH
  • 124
  • 1
  • 1
  • 10
  • 1
    You're looking for a _self-type_, which is unfortunately not possible to express in Java. At a minimum, `S extends SomeClass` might get you far enough along to proceed; otherwise, you'd still need casts. – chrylis -cautiouslyoptimistic- Jul 28 '21 at 19:13
  • 1
    If using java 15 or newer have a look at https://docs.oracle.com/en/java/javase/15/language/pattern-matching-instanceof-operator.html which describes binding a variable with instance of – Thorbjørn Ravn Andersen Jul 28 '21 at 19:20

0 Answers0