In Java, can I use a primitive type literal or type variable in an instanceof expression?

后端 未结 4 1785
后悔当初
后悔当初 2021-01-07 03:11

Can I use a primitive type literal or type variable in an instanceof expression?

class MyClass {
    {
         boolean b1 = null insta         


        
4条回答
  •  孤城傲影
    2021-01-07 03:46

    1. You can't do it.
    2. Even if you could, you can't use it.

    A typical usage of instanceof looks like

    void somemethod(Collection c) {
        if (c instanceof List) {...}
    }
    
    somemethod(new ArrayList());
    

    The important thing here is that you get an object of a supertype (here: Collection) which may or may not be instance of a subtype (here: List). With primitives this is impossible:

    void anothermethod(double x) {
        .... // <------ X
    }
    
    anothermethod(42);
    

    At the point X there's a variable x of type double, there's no hidden information about some int 42. The actual parameter 42 didn't masquerade as double, it's got converted to a double. That's why instanceof makes no sense for primitives.

提交回复
热议问题