How to replace run-time instanceof check with compile-time generics validation

前端 未结 6 903
有刺的猬
有刺的猬 2021-01-22 11:52

Got a little puzzle for a true Java Generics specialist... ;)

Let\'s say I have the following two interfaces:

interface Processor {
    void process(Foo          


        
6条回答
  •  暖寄归人
    2021-01-22 12:28

    Here's your code fully "genericized", but with one slight change: The INSTANCE variable is not static.

    interface Processor> {
        void process(T foo);
    }
    
    interface Foo> {
        Processor getProcessor();
    }
    
    static class SomeProcessor> implements Processor {
    
        final SomeProcessor INSTANCE = new SomeProcessor();
    
        @Override
        public void process(T foo) {
            // it will only ever be a SomeFoo if T is SomeFoo
        }
    }
    
    class SomeFoo implements Foo {
        @Override
        public Processor getProcessor() {
            return new SomeProcessor().INSTANCE;
        }
    }
    

    No compiler errors or warnings.

    INSTANCE was made an instance variable because class types do not make it through to static anything. If you really only wanted one INSTANCE, use the singleton pattern on the class.

提交回复
热议问题