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

前端 未结 6 901
有刺的猬
有刺的猬 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:23

    All that recursive bounds stuff is not necessary from a type safety point of view. Just something like this is sufficient:

    interface Processor {
        void process(F foo);
    }
    
    interface Foo {
        Processor getProcessor();
    }
    
    class SomeFoo implements Foo {
        @Override
        SomeProcessor getProcessor() { ... }
    }
    
    class SomeProcessor implements Processor {
        @Override
        void process(SomeFoo foo) { ... }
    }
    
    // in some other class:
    > void process(F foo) {
        foo.getProcessor().process(foo);
    }
    

    In other words: I'm looking for a way to define a function in an object such that it can only return another object that processes the type of object that contained the function. Note: I'm not just talking about processing some least common denominator super-class of the object containing the function (above: Foo), but that object's actual class (above: SomeFoo).

    That's not possible to declare in Java. Instead, as you see above, you can have a generic method outside the class (or be a static method of that class), which takes both the object and the processor, and enforces the types on both.


    Update: If you want to be able to call process with any Foo, then we can integrate meriton's idea of getThis() into this code also (again, without recursive bounds):

    interface Foo {
        Processor getProcessor();
        F getThis();
    }
    
    class SomeFoo implements Foo {
        SomeProcessor getProcessor() { ... }
        SomeFoo getThis() { return this; }
    }
    
    
    // in some other class:
     void process(Foo foo) {
        foo.getProcessor().process(foo.getThis());
    }
    

提交回复
热议问题