Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

java - Cannot perform instanceof check against parameterized type ArrayList<Foo>

The following code:

((tempVar instanceof ArrayList<Foo>) ? tempVar : null);

causes:

Cannot perform instanceof check against parameterized type ArrayList<Foo>. Use the form ArrayList<?> instead since further generic type information will be erased at runtime

Can someone explain me what is meant by "further generic type information will be erased at runtime" and how to fix this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It means that if you have anything that is parameterized, e.g. List<Foo> fooList = new ArrayList<Foo>();, the Generics information will be erased at runtime. Instead, this is what the JVM will see List fooList = new ArrayList();.

This is called type erasure. The JVM has no parameterized type information of the List (in the example) during runtime.

A fix? Since the JVM has no information of the Parameterized type on runtime, there's no way you can do an instanceof of ArrayList<Foo>. You can "store" the parameterized type explicitly and do a comparison there.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...