0

I have method with Stream object as argument, in that method i have to perform some actions based on Stream type. But instanceof is not working and gives me compile error

public <T>boolean objectIsNullOREmpty(Stream<T> str) {
    if(str instanceof Stream<String>) {
        //do some actions
    }

    if(Str instanceof Stream<SomeClass>) {
        //do some actions
    }
}

Compile Error

Cannot perform instanceof check against parameterized type Stream. Use the form Stream instead since further generic type information will be erased at runtime

Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98

2 Answers2

7

This is not a problem of streams. The error reflects the way that generic types were implemented in Java.

Java generic types are non-reifiable.

In Java, generic types have less type information available at run time than at compile time. This is so because generics are implemented in Java by erasure. Most of the generic type information exists only at compile time and is erased at run time.

For this reason, it is not possible to obtain a Class object for any non-reifiable type. The type information is not available at run time.

Not only can you not get a Class object for Stream<String>, but you can't get a Class object for any of T, List<T>, or List<String>. These are all non-reifiable types.

The instanceof operator will only work with types from which a Class object can be obtained. This is a good thing too, because List<T>, List<String>, and List<Integer> all share the same Class object at run time. It would be confusing and error prone if the following snippet evaluated to true:

List<String> strings = new ArrayList<>();
boolean b = strings instanceof List<Integer>;
System.out.println(b);

Instead, the Java compiler does not allow the use of the instanceof operator on non-reifiable types.

scottb
  • 9,908
  • 3
  • 40
  • 56
0

To add to @scottb's answer, if you really needed this structure then you would need separate methods. You cannot overload the methods either due to erasure, so you have to name each method such that the method signatures are unique:

public boolean stringIsNullOREmpty(Stream<String> str) {
    //do some actions
}    

public boolean someClassIsNullOREmpty(Stream<SomeClass> str) {
    //do some actions
}
flakes
  • 21,558
  • 8
  • 41
  • 88