How to run method on private field using reflectio

2020-03-31 03:05发布

问题:

I have a resource class as

public class SecureResource {

    private HttpServletRequest request;

    // some more things here
}

I would like to tun run request.getHeader('X-AUTH') using java reflection?

what I have tried?

Field f = response.getResourceClass().getDeclaredField("request");
f.setAccessible(true);
f.get("X-AUTH");

I get

java.lang.IllegalArgumentException: Can not set javax.servlet.http.HttpServletRequest field com.sn.bb.service.SecureResource.request to java.lang.String

What is that I am missing? How can I run request.getHeader('X-AUTH') on f?

回答1:

You're current trying to get the field as if it were a field on an instance of java.lang.String. Presumably you already have an instance of SecureResource, so you'd want to call:

Field f = response.getResourceClass().getDeclaredField("request");
f.setAccessible(true);
HttpServletRequest request = (HttpServletRequest) f.get(resource);
String auth = request.getHeader("X-AUTH");

(Where resource is a reference to the relevant instance of SecureResource.)

That said, even when you've got it working I'd strongly discourage it if at all possible. Your code won't work in scenarios where there's a strict security manager, it will be brittle in the face of a change of implementation, and it generally suggests you're trying to do something for which the class wasn't designed.