原始问题描述为How to run method on private field using reflection?
班级
public class SecureResource {
private HttpServletRequest request;
public SecureResource() {}
@Inject
public SecureResource(@Nonnull final HttpServletRequest request) {
this.request = request;
}
// more things
}
基于@Jon回答
(其中资源是对相关实例的引用 SecureResource。)
我做了以下
Class cls = response.getResourceClass();
Object obj = cls.newInstance();
Field f = cls.getDeclaredField("request");
f.setAccessible(true);
HttpServletRequest request = (HttpServletRequest) f.get(obj);
String auth = request.getHeader("X-AUTH");
我将request
作为null
且Field f
不为空
private javax.servlet.http.HttpServletRequest com.sunrunhome.blackbird.service.SecureResource.request
请告诉我这里我犯错的地方?
答案 0 :(得分:2)
代码是正确的,但是谁说request
不是假设是null
?向我们展示资源类的默认构造函数。 (注意:如果你依赖某些注射发生,它就不会。注射框架只有在你不规避它们时才有效。)