Error “illegal generic type for instanceof” when using local classes Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience Should we burninate the [wrap] tag? The Ask Question Wizard is Live!“illegal generic type of instanceof” when using instanceof on an inner class type?How to refer to a class when both simple and fully-qualified names clashCreate instance of generic type in Java?Calling a static method on a generic type parameterCollections.emptyList() returns a List<Object>?How to get the type of T from a member of a generic class or method?“illegal generic type of instanceof” when using instanceof on an inner class type?Get generic type of class at runtimeHow to get a class instance of generics type THow to make a Java Generic method static?Google Gson - deserialize list<class> object? (generic type)Get “Illegal generic type for instanceof” error when coparison

Identify plant with long narrow paired leaves and reddish stems

Why aren't air breathing engines used as small first stages

How to react to hostile behavior from a senior developer?

Do I really need recursive chmod to restrict access to a folder?

What is Arya's weapon design?

Output the ŋarâþ crîþ alphabet song without using (m)any letters

How would the world control an invulnerable immortal mass murderer?

Why are there no cargo aircraft with "flying wing" design?

51k Euros annually for a family of 4 in Berlin: Is it enough?

How to answer "Have you ever been terminated?"

Is there a (better) way to access $wpdb results?

What's the purpose of writing one's academic biography in the third person?

What does the "x" in "x86" represent?

Using et al. for a last / senior author rather than for a first author

The logistics of corpse disposal

Storing hydrofluoric acid before the invention of plastics

Why is my conclusion inconsistent with the van't Hoff equation?

Error "illegal generic type for instanceof" when using local classes

Why do people hide their license plates in the EU?

How can I make names more distinctive without making them longer?

Check which numbers satisfy the condition [A*B*C = A! + B! + C!]

What is a non-alternating simple group with big order, but relatively few conjugacy classes?

String `!23` is replaced with `docker` in command line

How discoverable are IPv6 addresses and AAAA names by potential attackers?



Error “illegal generic type for instanceof” when using local classes



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
Should we burninate the [wrap] tag?
The Ask Question Wizard is Live!“illegal generic type of instanceof” when using instanceof on an inner class type?How to refer to a class when both simple and fully-qualified names clashCreate instance of generic type in Java?Calling a static method on a generic type parameterCollections.emptyList() returns a List<Object>?How to get the type of T from a member of a generic class or method?“illegal generic type of instanceof” when using instanceof on an inner class type?Get generic type of class at runtimeHow to get a class instance of generics type THow to make a Java Generic method static?Google Gson - deserialize list<class> object? (generic type)Get “Illegal generic type for instanceof” error when coparison



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








31















I have the following Java code that uses a local class.



import java.util.Arrays;

public class X<T>
void m()
class Z

for (Object o : Arrays.asList(1, 2, 3))
if (o instanceof Z)




It does not compile with the following error message:



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


I understand that the local class Z inherits the generic type signature of X<T>, being an inner class. The same kind of compilation error appears in this example, where Z is not local, but still inner:



import java.util.Arrays;

public class X<T>
class Z

void m()
for (Object o : Arrays.asList(1, 2, 3))
if (o instanceof Z) // Compilation error




It can be worked around either by making Z non-inner / static:



import java.util.Arrays;

public class X<T>
static class Z

void m()
for (Object o : Arrays.asList(1, 2, 3))
if (o instanceof Z) // Compiles now




Or by qualifying X.Z:



import java.util.Arrays;

public class X<T>
class Z

void m()
for (Object o : Arrays.asList(1, 2, 3))
if (o instanceof X.Z) // Compiles now
if (o instanceof X<?>.Z) // Also





But how can I qualify a local class, or work around this limitation, without changing the local class itself?










share|improve this question
























  • I think this is a kind of compiler pathology. It's a strange way of telling you the type is not reifiable. It's even worse in Eclipse - it tells you "Use the form Z instead".

    – RealSkeptic
    15 hours ago






  • 1





    @RealSkeptic: Eclipse's compiler message is just "unlucky" here. It is usually a helpful extra information.

    – Lukas Eder
    15 hours ago






  • 2





    A corollary of this is that Z[] array = new Z[0]; is also illegal.

    – Andy Turner
    15 hours ago


















31















I have the following Java code that uses a local class.



import java.util.Arrays;

public class X<T>
void m()
class Z

for (Object o : Arrays.asList(1, 2, 3))
if (o instanceof Z)




It does not compile with the following error message:



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


I understand that the local class Z inherits the generic type signature of X<T>, being an inner class. The same kind of compilation error appears in this example, where Z is not local, but still inner:



import java.util.Arrays;

public class X<T>
class Z

void m()
for (Object o : Arrays.asList(1, 2, 3))
if (o instanceof Z) // Compilation error




It can be worked around either by making Z non-inner / static:



import java.util.Arrays;

public class X<T>
static class Z

void m()
for (Object o : Arrays.asList(1, 2, 3))
if (o instanceof Z) // Compiles now




Or by qualifying X.Z:



import java.util.Arrays;

public class X<T>
class Z

void m()
for (Object o : Arrays.asList(1, 2, 3))
if (o instanceof X.Z) // Compiles now
if (o instanceof X<?>.Z) // Also





But how can I qualify a local class, or work around this limitation, without changing the local class itself?










share|improve this question
























  • I think this is a kind of compiler pathology. It's a strange way of telling you the type is not reifiable. It's even worse in Eclipse - it tells you "Use the form Z instead".

    – RealSkeptic
    15 hours ago






  • 1





    @RealSkeptic: Eclipse's compiler message is just "unlucky" here. It is usually a helpful extra information.

    – Lukas Eder
    15 hours ago






  • 2





    A corollary of this is that Z[] array = new Z[0]; is also illegal.

    – Andy Turner
    15 hours ago














31












31








31


1






I have the following Java code that uses a local class.



import java.util.Arrays;

public class X<T>
void m()
class Z

for (Object o : Arrays.asList(1, 2, 3))
if (o instanceof Z)




It does not compile with the following error message:



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


I understand that the local class Z inherits the generic type signature of X<T>, being an inner class. The same kind of compilation error appears in this example, where Z is not local, but still inner:



import java.util.Arrays;

public class X<T>
class Z

void m()
for (Object o : Arrays.asList(1, 2, 3))
if (o instanceof Z) // Compilation error




It can be worked around either by making Z non-inner / static:



import java.util.Arrays;

public class X<T>
static class Z

void m()
for (Object o : Arrays.asList(1, 2, 3))
if (o instanceof Z) // Compiles now




Or by qualifying X.Z:



import java.util.Arrays;

public class X<T>
class Z

void m()
for (Object o : Arrays.asList(1, 2, 3))
if (o instanceof X.Z) // Compiles now
if (o instanceof X<?>.Z) // Also





But how can I qualify a local class, or work around this limitation, without changing the local class itself?










share|improve this question
















I have the following Java code that uses a local class.



import java.util.Arrays;

public class X<T>
void m()
class Z

for (Object o : Arrays.asList(1, 2, 3))
if (o instanceof Z)




It does not compile with the following error message:



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


I understand that the local class Z inherits the generic type signature of X<T>, being an inner class. The same kind of compilation error appears in this example, where Z is not local, but still inner:



import java.util.Arrays;

public class X<T>
class Z

void m()
for (Object o : Arrays.asList(1, 2, 3))
if (o instanceof Z) // Compilation error




It can be worked around either by making Z non-inner / static:



import java.util.Arrays;

public class X<T>
static class Z

void m()
for (Object o : Arrays.asList(1, 2, 3))
if (o instanceof Z) // Compiles now




Or by qualifying X.Z:



import java.util.Arrays;

public class X<T>
class Z

void m()
for (Object o : Arrays.asList(1, 2, 3))
if (o instanceof X.Z) // Compiles now
if (o instanceof X<?>.Z) // Also





But how can I qualify a local class, or work around this limitation, without changing the local class itself?







java generics local-class






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 56 mins ago









Peter Mortensen

13.9k1987114




13.9k1987114










asked 16 hours ago









Lukas EderLukas Eder

137k74448987




137k74448987












  • I think this is a kind of compiler pathology. It's a strange way of telling you the type is not reifiable. It's even worse in Eclipse - it tells you "Use the form Z instead".

    – RealSkeptic
    15 hours ago






  • 1





    @RealSkeptic: Eclipse's compiler message is just "unlucky" here. It is usually a helpful extra information.

    – Lukas Eder
    15 hours ago






  • 2





    A corollary of this is that Z[] array = new Z[0]; is also illegal.

    – Andy Turner
    15 hours ago


















  • I think this is a kind of compiler pathology. It's a strange way of telling you the type is not reifiable. It's even worse in Eclipse - it tells you "Use the form Z instead".

    – RealSkeptic
    15 hours ago






  • 1





    @RealSkeptic: Eclipse's compiler message is just "unlucky" here. It is usually a helpful extra information.

    – Lukas Eder
    15 hours ago






  • 2





    A corollary of this is that Z[] array = new Z[0]; is also illegal.

    – Andy Turner
    15 hours ago

















I think this is a kind of compiler pathology. It's a strange way of telling you the type is not reifiable. It's even worse in Eclipse - it tells you "Use the form Z instead".

– RealSkeptic
15 hours ago





I think this is a kind of compiler pathology. It's a strange way of telling you the type is not reifiable. It's even worse in Eclipse - it tells you "Use the form Z instead".

– RealSkeptic
15 hours ago




1




1





@RealSkeptic: Eclipse's compiler message is just "unlucky" here. It is usually a helpful extra information.

– Lukas Eder
15 hours ago





@RealSkeptic: Eclipse's compiler message is just "unlucky" here. It is usually a helpful extra information.

– Lukas Eder
15 hours ago




2




2





A corollary of this is that Z[] array = new Z[0]; is also illegal.

– Andy Turner
15 hours ago






A corollary of this is that Z[] array = new Z[0]; is also illegal.

– Andy Turner
15 hours ago













4 Answers
4






active

oldest

votes


















20














To me this seems to be an oversight or limitation in the Java language and I do not think it is possible.



The referenced type in an instanceof expression must be reifiable according to JLS 4.7, meaning that it must be expressed as a reifiable type by its fully qualified name. At the same time, JLS 6.7 states that local classes do not have a fully qualified name, they can therefore not be expressed as reifiable.



If you declare Z as generic, the instanceof operator treats Z as a raw type where all generic properties to it - in this case the enclosing class - are considered raw as well. (Similar to a generic methods of a raw type being considered as raw despite any generic signature. This is a measure to retain backwards compatiblity of type generification.) Since any raw type is reifiable, declaring Z to be generic will compile.






share|improve this answer

























  • It's true, but curiously, it does allow it if Z itself is generic, despite the fact that you have no way to qualify it.

    – RealSkeptic
    15 hours ago











  • "oversight" - You're here to pick a fight with the JLS designers, right? :)

    – Lukas Eder
    15 hours ago






  • 2





    Generics were patched into the language and there are some corner cases such as class literals that were not properly covered. Nothing is perfect, I think there is a chance for an oversight. ;)

    – Rafael Winterhalter
    15 hours ago











  • I extended my answer to explain why generification of Z does the trick.

    – Rafael Winterhalter
    15 hours ago











  • @LukasEder I think oversight is right. It's sort of like this question: these cases could have been designed around, but they haven't been; I make no judgment as to whether they should have been.

    – Andy Turner
    15 hours ago



















14














A possible workaround is to use reflection:



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))







share|improve this answer






























    2














    Apparently, by making Z generic compilation succeeds. I expected that to require <T> as the type parameter, but you just have to make it generic, so anything will do



    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))




    Proper solution would be qualify the local class, but I don't think you can. Either you refactor it to a private static class or that's probably the best you can get.






    share|improve this answer




















    • 2





      Once you make Z generic, you don't need to apply the reflection workaround anymore...

      – Lukas Eder
      15 hours ago


















    0














    This should work either. Using reflection too. But seems a valid solution.



    import java.util.Arrays;

    public class X<T>


    void m()

    class Z2


    for(Object o: Arrays.asList(1,2,3))
    if(Z2.class.isAssignableFrom(o.getClass()))












    share|improve this answer

























    • I didn't downvote, but I guess it's because there's a slightly better way to use reflection here, as I've mentioned in my own answer

      – Lukas Eder
      15 hours ago











    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55703849%2ferror-illegal-generic-type-for-instanceof-when-using-local-classes%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    4 Answers
    4






    active

    oldest

    votes








    4 Answers
    4






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    20














    To me this seems to be an oversight or limitation in the Java language and I do not think it is possible.



    The referenced type in an instanceof expression must be reifiable according to JLS 4.7, meaning that it must be expressed as a reifiable type by its fully qualified name. At the same time, JLS 6.7 states that local classes do not have a fully qualified name, they can therefore not be expressed as reifiable.



    If you declare Z as generic, the instanceof operator treats Z as a raw type where all generic properties to it - in this case the enclosing class - are considered raw as well. (Similar to a generic methods of a raw type being considered as raw despite any generic signature. This is a measure to retain backwards compatiblity of type generification.) Since any raw type is reifiable, declaring Z to be generic will compile.






    share|improve this answer

























    • It's true, but curiously, it does allow it if Z itself is generic, despite the fact that you have no way to qualify it.

      – RealSkeptic
      15 hours ago











    • "oversight" - You're here to pick a fight with the JLS designers, right? :)

      – Lukas Eder
      15 hours ago






    • 2





      Generics were patched into the language and there are some corner cases such as class literals that were not properly covered. Nothing is perfect, I think there is a chance for an oversight. ;)

      – Rafael Winterhalter
      15 hours ago











    • I extended my answer to explain why generification of Z does the trick.

      – Rafael Winterhalter
      15 hours ago











    • @LukasEder I think oversight is right. It's sort of like this question: these cases could have been designed around, but they haven't been; I make no judgment as to whether they should have been.

      – Andy Turner
      15 hours ago
















    20














    To me this seems to be an oversight or limitation in the Java language and I do not think it is possible.



    The referenced type in an instanceof expression must be reifiable according to JLS 4.7, meaning that it must be expressed as a reifiable type by its fully qualified name. At the same time, JLS 6.7 states that local classes do not have a fully qualified name, they can therefore not be expressed as reifiable.



    If you declare Z as generic, the instanceof operator treats Z as a raw type where all generic properties to it - in this case the enclosing class - are considered raw as well. (Similar to a generic methods of a raw type being considered as raw despite any generic signature. This is a measure to retain backwards compatiblity of type generification.) Since any raw type is reifiable, declaring Z to be generic will compile.






    share|improve this answer

























    • It's true, but curiously, it does allow it if Z itself is generic, despite the fact that you have no way to qualify it.

      – RealSkeptic
      15 hours ago











    • "oversight" - You're here to pick a fight with the JLS designers, right? :)

      – Lukas Eder
      15 hours ago






    • 2





      Generics were patched into the language and there are some corner cases such as class literals that were not properly covered. Nothing is perfect, I think there is a chance for an oversight. ;)

      – Rafael Winterhalter
      15 hours ago











    • I extended my answer to explain why generification of Z does the trick.

      – Rafael Winterhalter
      15 hours ago











    • @LukasEder I think oversight is right. It's sort of like this question: these cases could have been designed around, but they haven't been; I make no judgment as to whether they should have been.

      – Andy Turner
      15 hours ago














    20












    20








    20







    To me this seems to be an oversight or limitation in the Java language and I do not think it is possible.



    The referenced type in an instanceof expression must be reifiable according to JLS 4.7, meaning that it must be expressed as a reifiable type by its fully qualified name. At the same time, JLS 6.7 states that local classes do not have a fully qualified name, they can therefore not be expressed as reifiable.



    If you declare Z as generic, the instanceof operator treats Z as a raw type where all generic properties to it - in this case the enclosing class - are considered raw as well. (Similar to a generic methods of a raw type being considered as raw despite any generic signature. This is a measure to retain backwards compatiblity of type generification.) Since any raw type is reifiable, declaring Z to be generic will compile.






    share|improve this answer















    To me this seems to be an oversight or limitation in the Java language and I do not think it is possible.



    The referenced type in an instanceof expression must be reifiable according to JLS 4.7, meaning that it must be expressed as a reifiable type by its fully qualified name. At the same time, JLS 6.7 states that local classes do not have a fully qualified name, they can therefore not be expressed as reifiable.



    If you declare Z as generic, the instanceof operator treats Z as a raw type where all generic properties to it - in this case the enclosing class - are considered raw as well. (Similar to a generic methods of a raw type being considered as raw despite any generic signature. This is a measure to retain backwards compatiblity of type generification.) Since any raw type is reifiable, declaring Z to be generic will compile.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 14 hours ago

























    answered 15 hours ago









    Rafael WinterhalterRafael Winterhalter

    28.5k1368149




    28.5k1368149












    • It's true, but curiously, it does allow it if Z itself is generic, despite the fact that you have no way to qualify it.

      – RealSkeptic
      15 hours ago











    • "oversight" - You're here to pick a fight with the JLS designers, right? :)

      – Lukas Eder
      15 hours ago






    • 2





      Generics were patched into the language and there are some corner cases such as class literals that were not properly covered. Nothing is perfect, I think there is a chance for an oversight. ;)

      – Rafael Winterhalter
      15 hours ago











    • I extended my answer to explain why generification of Z does the trick.

      – Rafael Winterhalter
      15 hours ago











    • @LukasEder I think oversight is right. It's sort of like this question: these cases could have been designed around, but they haven't been; I make no judgment as to whether they should have been.

      – Andy Turner
      15 hours ago


















    • It's true, but curiously, it does allow it if Z itself is generic, despite the fact that you have no way to qualify it.

      – RealSkeptic
      15 hours ago











    • "oversight" - You're here to pick a fight with the JLS designers, right? :)

      – Lukas Eder
      15 hours ago






    • 2





      Generics were patched into the language and there are some corner cases such as class literals that were not properly covered. Nothing is perfect, I think there is a chance for an oversight. ;)

      – Rafael Winterhalter
      15 hours ago











    • I extended my answer to explain why generification of Z does the trick.

      – Rafael Winterhalter
      15 hours ago











    • @LukasEder I think oversight is right. It's sort of like this question: these cases could have been designed around, but they haven't been; I make no judgment as to whether they should have been.

      – Andy Turner
      15 hours ago

















    It's true, but curiously, it does allow it if Z itself is generic, despite the fact that you have no way to qualify it.

    – RealSkeptic
    15 hours ago





    It's true, but curiously, it does allow it if Z itself is generic, despite the fact that you have no way to qualify it.

    – RealSkeptic
    15 hours ago













    "oversight" - You're here to pick a fight with the JLS designers, right? :)

    – Lukas Eder
    15 hours ago





    "oversight" - You're here to pick a fight with the JLS designers, right? :)

    – Lukas Eder
    15 hours ago




    2




    2





    Generics were patched into the language and there are some corner cases such as class literals that were not properly covered. Nothing is perfect, I think there is a chance for an oversight. ;)

    – Rafael Winterhalter
    15 hours ago





    Generics were patched into the language and there are some corner cases such as class literals that were not properly covered. Nothing is perfect, I think there is a chance for an oversight. ;)

    – Rafael Winterhalter
    15 hours ago













    I extended my answer to explain why generification of Z does the trick.

    – Rafael Winterhalter
    15 hours ago





    I extended my answer to explain why generification of Z does the trick.

    – Rafael Winterhalter
    15 hours ago













    @LukasEder I think oversight is right. It's sort of like this question: these cases could have been designed around, but they haven't been; I make no judgment as to whether they should have been.

    – Andy Turner
    15 hours ago






    @LukasEder I think oversight is right. It's sort of like this question: these cases could have been designed around, but they haven't been; I make no judgment as to whether they should have been.

    – Andy Turner
    15 hours ago














    14














    A possible workaround is to use reflection:



    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))







    share|improve this answer



























      14














      A possible workaround is to use reflection:



      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))







      share|improve this answer

























        14












        14








        14







        A possible workaround is to use reflection:



        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))







        share|improve this answer













        A possible workaround is to use reflection:



        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))








        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 16 hours ago









        Lukas EderLukas Eder

        137k74448987




        137k74448987





















            2














            Apparently, by making Z generic compilation succeeds. I expected that to require <T> as the type parameter, but you just have to make it generic, so anything will do



            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))




            Proper solution would be qualify the local class, but I don't think you can. Either you refactor it to a private static class or that's probably the best you can get.






            share|improve this answer




















            • 2





              Once you make Z generic, you don't need to apply the reflection workaround anymore...

              – Lukas Eder
              15 hours ago















            2














            Apparently, by making Z generic compilation succeeds. I expected that to require <T> as the type parameter, but you just have to make it generic, so anything will do



            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))




            Proper solution would be qualify the local class, but I don't think you can. Either you refactor it to a private static class or that's probably the best you can get.






            share|improve this answer




















            • 2





              Once you make Z generic, you don't need to apply the reflection workaround anymore...

              – Lukas Eder
              15 hours ago













            2












            2








            2







            Apparently, by making Z generic compilation succeeds. I expected that to require <T> as the type parameter, but you just have to make it generic, so anything will do



            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))




            Proper solution would be qualify the local class, but I don't think you can. Either you refactor it to a private static class or that's probably the best you can get.






            share|improve this answer















            Apparently, by making Z generic compilation succeeds. I expected that to require <T> as the type parameter, but you just have to make it generic, so anything will do



            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))




            Proper solution would be qualify the local class, but I don't think you can. Either you refactor it to a private static class or that's probably the best you can get.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 15 hours ago

























            answered 15 hours ago









            Edoardo VacchiEdoardo Vacchi

            759715




            759715







            • 2





              Once you make Z generic, you don't need to apply the reflection workaround anymore...

              – Lukas Eder
              15 hours ago












            • 2





              Once you make Z generic, you don't need to apply the reflection workaround anymore...

              – Lukas Eder
              15 hours ago







            2




            2





            Once you make Z generic, you don't need to apply the reflection workaround anymore...

            – Lukas Eder
            15 hours ago





            Once you make Z generic, you don't need to apply the reflection workaround anymore...

            – Lukas Eder
            15 hours ago











            0














            This should work either. Using reflection too. But seems a valid solution.



            import java.util.Arrays;

            public class X<T>


            void m()

            class Z2


            for(Object o: Arrays.asList(1,2,3))
            if(Z2.class.isAssignableFrom(o.getClass()))












            share|improve this answer

























            • I didn't downvote, but I guess it's because there's a slightly better way to use reflection here, as I've mentioned in my own answer

              – Lukas Eder
              15 hours ago















            0














            This should work either. Using reflection too. But seems a valid solution.



            import java.util.Arrays;

            public class X<T>


            void m()

            class Z2


            for(Object o: Arrays.asList(1,2,3))
            if(Z2.class.isAssignableFrom(o.getClass()))












            share|improve this answer

























            • I didn't downvote, but I guess it's because there's a slightly better way to use reflection here, as I've mentioned in my own answer

              – Lukas Eder
              15 hours ago













            0












            0








            0







            This should work either. Using reflection too. But seems a valid solution.



            import java.util.Arrays;

            public class X<T>


            void m()

            class Z2


            for(Object o: Arrays.asList(1,2,3))
            if(Z2.class.isAssignableFrom(o.getClass()))












            share|improve this answer















            This should work either. Using reflection too. But seems a valid solution.



            import java.util.Arrays;

            public class X<T>


            void m()

            class Z2


            for(Object o: Arrays.asList(1,2,3))
            if(Z2.class.isAssignableFrom(o.getClass()))













            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 15 hours ago









            Mark Rotteveel

            62.2k1479123




            62.2k1479123










            answered 15 hours ago









            JWThewesJWThewes

            191




            191












            • I didn't downvote, but I guess it's because there's a slightly better way to use reflection here, as I've mentioned in my own answer

              – Lukas Eder
              15 hours ago

















            • I didn't downvote, but I guess it's because there's a slightly better way to use reflection here, as I've mentioned in my own answer

              – Lukas Eder
              15 hours ago
















            I didn't downvote, but I guess it's because there's a slightly better way to use reflection here, as I've mentioned in my own answer

            – Lukas Eder
            15 hours ago





            I didn't downvote, but I guess it's because there's a slightly better way to use reflection here, as I've mentioned in my own answer

            – Lukas Eder
            15 hours ago

















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55703849%2ferror-illegal-generic-type-for-instanceof-when-using-local-classes%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            На ростанях Змест Гісторыя напісання | Месца дзеяння | Час дзеяння | Назва | Праблематыка трылогіі | Аўтабіяграфічнасць | Трылогія ў тэатры і кіно | Пераклады | У культуры | Зноскі Літаратура | Спасылкі | НавігацыяДагледжаная версіяправерана1 зменаДагледжаная версіяправерана1 зменаАкадэмік МІЦКЕВІЧ Канстанцін Міхайлавіч (Якуб Колас) Прадмова М. І. Мушынскага, доктара філалагічных навук, члена-карэспандэнта Нацыянальнай акадэміі навук Рэспублікі Беларусь, прафесараНашаніўцы ў трылогіі Якуба Коласа «На ростанях»: вобразы і прататыпы125 лет Янке МавруКнижно-документальная выставка к 125-летию со дня рождения Якуба Коласа (1882—1956)Колас Якуб. Новая зямля (паэма), На ростанях (трылогія). Сулкоўскі Уладзімір. Радзіма Якуба Коласа (серыял жывапісных палотнаў)Вокладка кнігіІлюстрацыя М. С. БасалыгіНа ростаняхАўдыёверсія трылогііВ. Жолтак У Люсiнскай школе 1959

            Францішак Багушэвіч Змест Сям'я | Біяграфія | Творчасць | Мова Багушэвіча | Ацэнкі дзейнасці | Цікавыя факты | Спадчына | Выбраная бібліяграфія | Ушанаванне памяці | У філатэліі | Зноскі | Літаратура | Спасылкі | НавігацыяЛяхоўскі У. Рупіўся дзеля Бога і людзей: Жыццёвы шлях Лявона Вітан-Дубейкаўскага // Вольскі і Памідораў з песняй пра немца Адвакат, паэт, народны заступнік Ашмянскі веснікВ Минске появится площадь Богушевича и улица Сырокомли, Белорусская деловая газета, 19 июля 2001 г.Айцец беларускай нацыянальнай ідэі паўстаў у бронзе Сяргей Аляксандравіч Адашкевіч (1918, Мінск). 80-я гады. Бюст «Францішак Багушэвіч».Яўген Мікалаевіч Ціхановіч. «Партрэт Францішка Багушэвіча»Мікола Мікалаевіч Купава. «Партрэт зачынальніка новай беларускай літаратуры Францішка Багушэвіча»Уладзімір Іванавіч Мелехаў. На помніку «Змагарам за родную мову» Барэльеф «Францішак Багушэвіч»Памяць пра Багушэвіча на Віленшчыне Страчаная сталіца. Беларускія шыльды на вуліцах Вільні«Krynica». Ideologia i przywódcy białoruskiego katolicyzmuФранцішак БагушэвічТворы на knihi.comТворы Францішка Багушэвіча на bellib.byСодаль Уладзімір. Францішак Багушэвіч на Лідчыне;Луцкевіч Антон. Жыцьцё і творчасьць Фр. Багушэвіча ў успамінах ягоных сучасьнікаў // Запісы Беларускага Навуковага таварыства. Вільня, 1938. Сшытак 1. С. 16-34.Большая российская1188761710000 0000 5537 633Xn9209310021619551927869394п

            Беларусь Змест Назва Гісторыя Геаграфія Сімволіка Дзяржаўны лад Палітычныя партыі Міжнароднае становішча і знешняя палітыка Адміністрацыйны падзел Насельніцтва Эканоміка Культура і грамадства Сацыяльная сфера Узброеныя сілы Заўвагі Літаратура Спасылкі НавігацыяHGЯOiТоп-2011 г. (па версіі ej.by)Топ-2013 г. (па версіі ej.by)Топ-2016 г. (па версіі ej.by)Топ-2017 г. (па версіі ej.by)Нацыянальны статыстычны камітэт Рэспублікі БеларусьШчыльнасць насельніцтва па краінахhttp://naviny.by/rubrics/society/2011/09/16/ic_articles_116_175144/А. Калечыц, У. Ксяндзоў. Спробы засялення краю неандэртальскім чалавекам.І ў Менску былі мамантыА. Калечыц, У. Ксяндзоў. Старажытны каменны век (палеаліт). Першапачатковае засяленне тэрыторыіГ. Штыхаў. Балты і славяне ў VI—VIII стст.М. Клімаў. Полацкае княства ў IX—XI стст.Г. Штыхаў, В. Ляўко. Палітычная гісторыя Полацкай зямліГ. Штыхаў. Дзяржаўны лад у землях-княствахГ. Штыхаў. Дзяржаўны лад у землях-княствахБеларускія землі ў складзе Вялікага Княства ЛітоўскагаЛюблінская унія 1569 г."The Early Stages of Independence"Zapomniane prawdy25 гадоў таму было аб'яўлена, што Язэп Пілсудскі — беларус (фота)Наша вадаДакументы ЧАЭС: Забруджванне тэрыторыі Беларусі « ЧАЭС Зона адчужэнняСведения о политических партиях, зарегистрированных в Республике Беларусь // Министерство юстиции Республики БеларусьСтатыстычны бюлетэнь „Полаўзроставая структура насельніцтва Рэспублікі Беларусь на 1 студзеня 2012 года і сярэднегадовая колькасць насельніцтва за 2011 год“Индекс человеческого развития Беларуси — не было бы нижеБеларусь занимает первое место в СНГ по индексу развития с учетом гендерного факцёраНацыянальны статыстычны камітэт Рэспублікі БеларусьКанстытуцыя РБ. Артыкул 17Трансфармацыйныя задачы БеларусіВыйсце з крызісу — далейшае рэфармаванне Беларускі рубель — сусветны лідар па дэвальвацыяхПра змену коштаў у кастрычніку 2011 г.Бядней за беларусаў у СНД толькі таджыкіСярэдні заробак у верасні дасягнуў 2,26 мільёна рублёўЭканомікаГаласуем за ТОП-100 беларускай прозыСучасныя беларускія мастакіАрхитектура Беларуси BELARUS.BYА. Каханоўскі. Культура Беларусі ўсярэдзіне XVII—XVIII ст.Анталогія беларускай народнай песні, гуказапісы спеваўБеларускія Музычныя IнструментыБеларускі рок, які мы страцілі. Топ-10 гуртоў«Мясцовы час» — нязгаслая легенда беларускай рок-музыкіСЯРГЕЙ БУДКІН. МЫ НЯ ЗНАЕМ СВАЁЙ МУЗЫКІМ. А. Каладзінскі. НАРОДНЫ ТЭАТРМагнацкія культурныя цэнтрыПублічная дыскусія «Беларуская новая пьеса: без беларускай мовы ці беларуская?»Беларускія драматургі па-ранейшаму лепш ставяцца за мяжой, чым на радзіме«Працэс незалежнага кіно пайшоў, і дзяржаву турбуе яго непадкантрольнасць»Беларускія філосафы ў пошуках прасторыВсе идём в библиотекуАрхіваванаАб Нацыянальнай праграме даследавання і выкарыстання касмічнай прасторы ў мірных мэтах на 2008—2012 гадыУ космас — разам.У суседнім з Барысаўскім раёне пабудуюць Камандна-вымяральны пунктСвяты і абрады беларусаў«Мірныя бульбашы з малой краіны» — 5 непраўдзівых стэрэатыпаў пра БеларусьМ. Раманюк. Беларускае народнае адзеннеУ Беларусі скарачаецца колькасць злачынстваўЛукашэнка незадаволены мінскімі ўладамі Крадзяжы складаюць у Мінску каля 70% злачынстваў Узровень злачыннасці ў Мінскай вобласці — адзін з самых высокіх у краіне Генпракуратура аналізуе стан са злачыннасцю ў Беларусі па каэфіцыенце злачыннасці У Беларусі стабілізавалася крымінагеннае становішча, лічыць генпракурорЗамежнікі сталі здзяйсняць у Беларусі больш злачынстваўМУС Беларусі турбуе рост рэцыдыўнай злачыннасціЯ з ЖЭСа. Дазволіце вас абкрасці! Рэйтынг усіх службаў і падраздзяленняў ГУУС Мінгарвыканкама вырасАб КДБ РБГісторыя Аператыўна-аналітычнага цэнтра РБГісторыя ДКФРТаможняagentura.ruБеларусьBelarus.by — Афіцыйны сайт Рэспублікі БеларусьСайт урада БеларусіRadzima.org — Збор архітэктурных помнікаў, гісторыя Беларусі«Глобус Беларуси»Гербы и флаги БеларусиАсаблівасці каменнага веку на БеларусіА. Калечыц, У. Ксяндзоў. Старажытны каменны век (палеаліт). Першапачатковае засяленне тэрыторыіУ. Ксяндзоў. Сярэдні каменны век (мезаліт). Засяленне краю плямёнамі паляўнічых, рыбакоў і збіральнікаўА. Калечыц, М. Чарняўскі. Плямёны на тэрыторыі Беларусі ў новым каменным веку (неаліце)А. Калечыц, У. Ксяндзоў, М. Чарняўскі. Гаспадарчыя заняткі ў каменным векуЭ. Зайкоўскі. Духоўная культура ў каменным векуАсаблівасці бронзавага веку на БеларусіФарміраванне супольнасцей ранняга перыяду бронзавага векуФотографии БеларусиРоля беларускіх зямель ва ўтварэнні і ўмацаванні ВКЛВ. Фадзеева. З гісторыі развіцця беларускай народнай вышыўкіDMOZGran catalanaБольшая российскаяBritannica (анлайн)Швейцарскі гістарычны15325917611952699xDA123282154079143-90000 0001 2171 2080n9112870100577502ge128882171858027501086026362074122714179пппппп