简体   繁体   English

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

[英]NullPointerException while trying to invoke method on private field using Reflection

The original issue is described How to run method on private field using reflection? 原始问题描述如何使用反射在私有字段上运行方法?

The class is 这堂课是

public class SecureResource {

    private HttpServletRequest request;
        public SecureResource() {}

    @Inject
    public SecureResource(@Nonnull final HttpServletRequest request) {
        this.request = request;
    }
    // more things
}

Based on @Jon answer 基于@Jon回答

(Where resource is a reference to the relevant instance of SecureResource.) (其中resource是对SecureResource的相关实例的引用。)

I did the following 我做了以下

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

and I get request as null 我得到requestnull

and the Field f is not null 并且Field f不为空

private javax.servlet.http.HttpServletRequest com.sunrunhome.blackbird.service.SecureResource.request

Please let me know where I am making mistakes here? 请让我知道我在哪里犯错误?

The code is correct as written, but who says that request isn't supposed to be null ? 编写的代码是正确的,但是谁说request应该null Show us the default constructor of your resource class. 向我们展示资源类的默认构造函数。 (Note: if you're relying on some injection to happen, it won't. Injection frameworks only work when you don't circumvent them.) (注意:如果您依赖某些注入发生,它就不会。注入框架仅在您不绕过它们时才起作用。)

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

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