Java 访问超类中的局部变量';子类中重写的方法中的
Java中有没有一种方法,通过反射或其他方式,从子类中相应的重写方法访问超类方法中声明的局部变量 具体来说,我正在使用Spring Security的Java 访问超类中的局部变量';子类中重写的方法中的,java,spring,reflection,spring-security,Java,Spring,Reflection,Spring Security,Java中有没有一种方法,通过反射或其他方式,从子类中相应的重写方法访问超类方法中声明的局部变量 具体来说,我正在使用Spring Security的DefaultLdapAuthoritiesPopulator。这个类有一个名为getAdditionalRoles的方法,文档中说子类可以重写该方法,为用户返回额外的角色 该类还实现了getGrantedAuthories方法,该方法实际上调用了getAdditionalRoles方法。源代码如下所示: public final GrantedA
DefaultLdapAuthoritiesPopulator
。这个类有一个名为getAdditionalRoles
的方法,文档中说子类可以重写该方法,为用户返回额外的角色
该类还实现了getGrantedAuthories
方法,该方法实际上调用了getAdditionalRoles
方法。源代码如下所示:
public final GrantedAuthority[] getGrantedAuthorities(DirContextOperations user, String username) {
...
Set roles = getGroupMembershipRoles(userDn, username);
Set extraRoles = getAdditionalRoles(user, username);
...
}
此方法调用getGroupMembershipRoles
,它对为此用户定义的组执行LDAP搜索,并将其存储在名为roles
的局部变量中。现在,在我的getAdditionalRoles
实现中,我还需要访问LDAP中为此用户定义的组,以便推断此用户的其他角色。出于业务原因,我无法直接在LDAP中定义这些附加角色
我可以直接自己实现
ldapaauthorities populator
,但我想知道是否还有其他方法,因为我真正需要的是访问父类方法中的角色
局部变量,以避免我必须进行第二次LDAP搜索。可能您可以利用AOP并在重新调整getGroupMembershipRoles(userDn,username)的建议后放置编码>并修改返回的角色。可能您可以利用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;
}
@覆盖
公共集getGroupMembershipRoles(字符串userDn,
字符串(用户名){
Set authorities=super.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;
}
@覆盖
公共集getGroupMembershipRoles(字符串userDn,
字符串(用户名){
Set authorities=super.getGroupMembershipRoles(userDn,username);
//通过检查权限设置,我的应用程序的逻辑
返回当局;
}
我认为您无法从其他远程类中存在的任何方法(who的value方法不返回)访问来自局部变量的数据。在这种情况下,即使是反思也无济于事。如果我错了或遗漏了什么,请纠正我。我认为您无法从其他远程类中存在的任何方法(who的value方法不返回)访问来自局部变量的数据。在这种情况下,即使是反思也无济于事。如果我错了或遗漏了什么,请纠正我
您不能访问其他方法中的变量,因为方法中的变量在返回该方法后会被删除。因为变量在堆栈中
如果可能,您可以重写getGroupMembershipRoles
并将groups
存储为属性,并通过其他方法访问它
您不能访问其他方法中的变量,因为方法中的变量在返回该方法后会被删除。因为变量在堆栈中
如果可能,您可以重写getGroupMembershipRoles
并将groups
存储为属性,并通过其他方法访问它
你不能重写getGroupMembershipRoles()
?好的观点。我可以做到。出于某种原因,我觉得该方法在父级中被声明为final。这将减少复制/粘贴,而不是重新执行整个类。您不能覆盖getGroupMembershipRoles()
?这一点很好。我可以做到。出于某种原因,我觉得该方法在父级中被声明为final。这将减少复制/粘贴,而不是重新执行整个类。