Avoiding generic types of form Foo>

后端 未结 2 415
北荒
北荒 2020-12-11 15:50

I frequently find myself wanting to write generic class definitions of the form

public class Foo

        
2条回答
  •  隐瞒了意图╮
    2020-12-11 16:37

    I would recommend that we simply use to represent the "self type". No need for bound, since it looks complicated, doesn't deliver the intention, and cannot enforce the constraint anyway.

    public class Foo {
    
        private final List> handlers = new ArrayList<>();
    
        public void addChangeHandler(ChangeHandler handler) {
            handlers.add(handler);
        }
    
        @SuppressWarnings("unchecked")
        protected void reportChange() {
            for (ChangeHandler handler: handlers)
                handler.onChange( (This)this );
        }
    }
    

    Notice the cast (This)this.

    See also Java generics: Use this type as return type?

提交回复
热议问题