Java Generics Hell

前端 未结 2 1826
忘掉有多难
忘掉有多难 2021-01-31 09:18

I suspect this has been asked here (and answered) before, but I don\'t know how to name the problem. Why can I express the wildcards without problem only when I\'m not passing

2条回答
  •  没有蜡笔的小新
    2021-01-31 10:07

    Typing the genericsHell method allows it to compile:

    static > void genericsHell(Class a) {}
    

    EDITED: This allows the compiler to specify from context, or by coding an explicit type, that the ShapeProcessor is not literally any ShapeProcessor, but the same type as the one passed as a parameter. If the call was explicitly typed, (which the compiler does under the covers) the code would look like this:

    MyClass.genericsHell(ShapeSaver.class);
    

    Which interestingly, gives a type warning, but still compiles. The explicit type is not required however because sufficient type information is available from the parameter to infer the generic type.


    Your question is missing some declarations, so I added them in to create a Short Self-Contained Correct Example - ie this code compiles as-is

    static interface Shape { }
    
    static interface Circle extends Shape { }
    
    static interface ShapeProcessor { }
    
    static class CircleDrawer implements ShapeProcessor { }
    
    static class ShapeSaver implements ShapeProcessor { }
    
    static void genericsHeaven(ShapeProcessor a) { }
    
    // The change was made to this method signature:
    static > void genericsHell(Class a) { }
    
    static void test() {
        genericsHeaven(new CircleDrawer());
        genericsHeaven(new ShapeSaver());
        genericsHell(CircleDrawer.class);
        genericsHell(ShapeSaver.class);
    }
    

提交回复
热议问题