开发者

Anonymous inner class and fields outside of that block of code

With anonymous inner classes, how does Java treat fields that are declared outside of the anonymous inner class block.

In the case policyOwnerModelObject, how is that field defined in the generated anonymous inner class?

// Local variable
final Bean policyOwnerModelObject = XXXXX <--- here, how is the class built with access to this object.  Is it a final field in the class?

    final WebMarkupContainer container = new WebMarkupContainer("container") {            
            @Override
            public boolean isVisible() {                
                if ((policyOwnerModelObject.getPolicyOwner() != null) && (policyOwnerMod开发者_Python百科elObject.getPolicyOwner().getValue() != null)) {
                    return !PolicyOwnerService.TRUST.equals(policyOwnerModelObject.getPolicyOwner().getValue());
                } else {
                    return false;
                }
            } 
        }; 

====

OK, decompiled the class and this is what I got:

class MyDataPanel$1 extends WebMarkupContainer
{

    public boolean isVisible()
    {
        if(val$policyOwnerModelObject.getMy() != null && val$policyOwnerModelObject.getMy().getValue() != null)
            return !"4".equals(val$policyOwnerModelObject.getMy().getValue());
        else
            return false;
    }

    final MyDataPanel this$0;
    private final MyBean val$policyOwnerModelObject;

    MyDataPanel$1(MyBean policyownerbean)
    {
        this$0 = final_policytrustpanel;
        val$policyOwnerModelObject = policyownerbean;
        super(String.this);
    }
}


Here private Bean policyOwnerModelObject is just a regular member of the class. The variable doesn't have to be final in this case, because it will never go out of scope before the anonymous class does. The inner class will have full access to the variable as if it were a member of that inner class.

In general (anonymous or not) inner classes have full access to member variables of their parent classes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜