Java “The blank final field may not have been initialized” Anonymous Interface vs Lambda Expression

前端 未结 4 2132
余生分开走
余生分开走 2020-12-06 15:49

I\'ve recently been encountering the error message \"The blank final field obj may not have been initialized\".

Usually this is the case if you try to refer to a field t

4条回答
  •  没有蜡笔的小新
    2020-12-06 16:46

    I had a similar problem:

    import java.util.function.Supplier;
    
    public class ObjectHolder {
        private final Object obj;
        public Supplier sup = () -> obj; // error
    
        public ObjectHolder(Object obj) {
            this.obj = obj;
        }
    }
    
    
    

    And resolved it this way:

    public Supplier sup = () -> ((ObjectHolder)this).obj;
    
    
    

    Neither this.obj nor ObjectHolder.this.obj worked in Eclipse (though the latter worked for the standard JDK compiler).

    In your case, use this workaround, it is safe for all compilers:

    ((Foo)this).obj.toString();
    

    Another solution is to use a getter. In my example, it looks like this:

    public Supplier sup = () -> getObj();
    
    private Object getObj() {
        return obj;
    }
    
        

    提交回复
    热议问题