What is the 'instanceof' operator used for in Java?

前端 未结 17 1222
梦毁少年i
梦毁少年i 2020-11-22 03:03

What is the instanceof operator used for? I\'ve seen stuff like

if (source instanceof Button) {
    //...
} else {
    //...
}

17条回答
  •  孤城傲影
    2020-11-22 04:04

    You could use Map to make higher abstraction on instance of

    private final Map> actions = new HashMap<>();
    

    Then having such map add some action to it:

    actions.put(String.class, new Consumer() {
            @Override
            public void accept(String s) {
               System.out.println("action for String");       
            }
        };
    

    Then having an Object of not known type you could get specific action from that map:

    actions.get(someObject).accept(someObject)
    

提交回复
热议问题