繁体   English   中英

从子类中的重写方法访问超类方法中的局部变量

[英]Access a local variable in the superclass' method from the overridden method in the subclass

在Java中,是否可以通过反射或其他方式从子类中对应的重写方法访问超类的方法中声明的局部变量?

具体来说,我正在使用Spring Security的DefaultLdapAuthoritiesPopulator 此类具有一个名为getAdditionalRoles的方法,该文档称该方法可以重写子类以为用户返回额外的角色。

该类还实现了getGrantedAuthorities方法,该方法实际上调用了getAdditionalRoles方法。 源代码如下所示:

public final GrantedAuthority[] getGrantedAuthorities(DirContextOperations user, String username) {
    ...
    Set roles = getGroupMembershipRoles(userDn, username);

    Set extraRoles = getAdditionalRoles(user, username);

    ...
}

此方法调用getGroupMembershipRoles ,该方法getGroupMembershipRoles为此用户定义的组进行LDAP搜索,并将其存储在名为roles的本地变量roles 现在,在实现getAdditionalRoles ,我还需要访问为此用户在LDAP中定义的组,因此可以推断出该用户的其他角色。 出于业务原因,我无法直接在LDAP中定义这些其他角色。

我可以自己继续实施LdapAuthoritiesPopulator ,但我想知道是否还有其他方法,因为我真正需要的是访问父类方法中的roles局部变量,以避免我不得不进行第二次LDAP搜索。

  1. 您无法访问其他方法中的变量,因为方法返回后,方法中的变量将被删除。 因为变量在堆栈中。
  2. 如果可能,您可以覆盖getGroupMembershipRoles并获取存储为属性的groups ,并以其他方法访问它。

可能您可以利用AOP并将“调整建议后”放到getGroupMembershipRoles(userDn, username); 并修改返回的角色。

我接受了Zutty的建议并以这种方式实施了它:

@Override
public Set<GrantedAuthority> getGroupMembershipRoles(String userDn,
        String username) {
    Set<GrantedAuthority> authorities = super.getGroupMembershipRoles(userDn, username);

    // My app's logic by inspecting the authorities Set

    return authorities;

}

我不认为您可以通过任何其他远程类中存在的任何方法(谁的value方法不返回)从局部变量访问数据。 在这种情况下,即使反思也无济于事。 如果我错了或错过了什么,请纠正我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM