尝试使用Reflection在私有字段上调用方法时出现NullPointerException

时间:2013-08-27 21:47:03

标签: java reflection

原始问题描述为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

请告诉我这里我犯错的地方?

1 个答案:

答案 0 :(得分:2)

代码是正确的,但是谁说request不是假设null?向我们展示资源类的默认构造函数。 (注意:如果你依赖某些注射发生,它就不会。注射框架只有在你不规避它们时才有效。)