简体   繁体   中英

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

(Where resource is a reference to the relevant instance of 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

and the Field f is not null

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 ? 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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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