[Solved] Java Error illegal generic type for instanceof

(254 Views)


We have a local class Z which needs to be used as below:

import java.util.Arrays; public class X<T> { void m() { class Z {} for (Object o : Arrays.asList(1, 2, 3)) if (o instanceof Z) {} } }

Problem:

On compiling above code it throws error , which is :

X.java:8: error: illegal generic type for instanceof if (o instanceof Z) {} ^

In Java, there is no fully qualified name for local classes, thus they cannot be expressed as Reifiable (A reifiable type is a type whose type information is fully available at runtime. This includes primitives, non-generic types, raw types, and invocations of unbound wildcards). And in an instanceof expression the referenced type must be Reifiable. Now lets see how do we resolve this error.

Solution 1 :

A simple solution is to use reflection, using reflection you can use the local class without any changes.

import java.util.Arrays; public class X<T> { void m() { class Z {} for (Object o : Arrays.asList(1, 2, 3)) if (Z.class.isInstance(o)) {} } }

Solution 2 :

Another way to resolve this error is to make class Z generic.

import java.util.Arrays; public class X<T> { void m() { class Z<Anything> {} for (Object o : Arrays.asList(1, 2, 3)) if (Z.class.isInstance(o)) {} } }

Solution Worked 1 UpvotesUpvote

        

Solution Didn't Worked 0 DownvotesDownvote



Comments



Search
Play 2048 Game Online

Search Tags

    illegal generic type for instanceof Solution