我有Stream
的方法对象作为参数,在该方法中我必须根据 Stream
执行一些操作类型。但是instanceof
不工作并给我编译错误
public <T>boolean objectIsNullOREmpty(Stream<T> str) {
if(str instanceof Stream<String>) {
//do some actions
}
if(Str instanceof Stream<SomeClass>) {
//do some actions
}
}
编译错误
Cannot perform instanceof check against parameterized type Stream. Use the form Stream instead since further generic type information will be erased at runtime
最佳答案
这不是流的问题。该错误反射(reflect)了 Java 中泛型类型的实现方式。
Java 泛型类型不可具体化。
在 Java 中,泛型类型在运行时的可用类型信息少于编译时的类型信息。之所以如此,是因为 Java 中的泛型是通过删除来实现的。大多数泛型类型信息仅在编译时存在,并在运行时被删除。
因此,无法获得 Class
任何不可具体化类型的对象。类型信息在运行时不可用。
你不但得不到Class
对象 Stream<String>
,但你无法得到Class
T
中任何一个的对象, List<T>
,或List<String>
。这些都是不可具体化的类型。
instanceof 运算符仅适用于 Class
的类型。可以获得对象。这也是一件好事,因为List<T>
, List<String>
,和List<Integer>
它们在运行时共享相同的 Class 对象。如果以下代码片段的计算结果为true
,则会令人困惑且容易出错。 :
List<String> strings = new ArrayList<>();
boolean b = strings instanceof List<Integer>;
System.out.println(b);
相反,Java 编译器不允许使用 instanceof
不可具体化类型的运算符。
关于java - 如何在java-8中查找流类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53640472/