What can replace instanceof for java 11?

@Override
public int compareTo(@NotNull Object o) {
    if (o instanceof Task task) {
        if (task.getStartTime() == null) {
            return -1;
        } else if (task.getStartTime().isBefore(this.startTime)) {
            return 1;
        } else if (task.getStartTime().isAfter(this.startTime)) {
            return -1;
        } else return 0;
    } else throw new RuntimeException("Не наследник Task");
}
java: pattern matching in instanceof is not supported in -source 11
  (use -source 16 or higher to enable pattern matching in instanceof)

I can use only Java 11. How can I resolve this?

>Solution :

Change your code to this:

@Override
public int compareTo(@NotNull Object o) {
    if (o instanceof Task) {
        final Task task = (Task) o;
        if (task.getStartTime() == null) {
            return -1;
        } else if (task.getStartTime().isBefore(this.startTime)) {
            return 1;
        } else if (task.getStartTime().isAfter(this.startTime)) {
            return -1;
        } else return 0;
    } else throw new RuntimeException("Не наследник Task");
}

Prior to pattern matching you had to cast the class manually.

Leave a Reply