Extensive type erasures in generic classes

iwek :

For some time I thought I have understanding of how type erasure and generic types worked but today I stumbled upon case when generic type is used in class and unexpected type erasures happen even on types not related to generic. Consider following example class:

import java.util.Optional;

class TheClass<T> {
    Optional<Something> getSomething() {
        return Optional.of(new Something());
    }

    class Something {
        int getId() {
            return 1;
        }
    }
}

Notably it has generic that is not used at all. Class usage is following:

public class Main {
    private static TheClass clazz = new TheClass<>();

    public static void main(String[] args) {
        clazz.getSomething().ifPresent(s -> System.out.println(((TheClass.Something) s).getId()));
    }
}

clazz.getSomething().ifPresent produces warning (unchecked call to ifPresent) and inside call to if present cast is needed. If generic T is removed from abstract class then code works as expected without warning and cast.

What is the reason of observed behavior? Why javac seemingly earses all types from TheClass? Is there any workaround to avoid casting arguments and supressing uchecked warning?

Laksitha Ranasingha :

The problem is your clazz static instance is still raw.

The compiler cannot workout the generic type even though you have specified the diamond operator because the left hand side is raw.

The raw classes lose all generics. There are two options, you could do.

  1. Use the specific type, Something in this case (However, you will have to declare it static in because you refer it in the static context). For this exercise, I have made class Something static,
  static class Something {
        int getId() {
            return 1;
        }
  }
    private static TheClass<Something> clazz = new TheClass<>();

    public static void main(String[] args) {
        clazz.getSomething().ifPresent(s -> System.out.println(s.getId()));
    }
  1. Or use wildcard as MC Emperor's answer.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=143162&siteId=1