2

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);

    ...
}

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

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

4

4 回答 4

2
  1. 您不能访问其他方法中的变量,因为方法中的变量在方法返回后被删除。因为变量在堆栈中。
  2. 如果可能,您可以覆盖getGroupMembershipRolesgroups存储为属性,并以其他方法访问它。
于 2013-03-22T02:21:29.087 回答
1

可能您可以利用 AOP 并设置After Retuning AdvicegetGroupMembershipRoles(userDn, username);修改返回的角色。

于 2013-03-21T17:03:31.227 回答
1

我接受了 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;

}
于 2013-03-21T17:11:01.007 回答
0

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

于 2013-03-21T17:12:46.423 回答