简体   繁体   English

如何使用反射在私有字段上运行方法?

[英]How to run method on private field using reflection?

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? 我想使用Java反射来调整运行request.getHeader('X-AUTH')吗?

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 ? 如何在f上运行request.getHeader('X-AUTH')

You're current trying to get the field as if it were a field on an instance of java.lang.String . 您当前正在尝试获取字段 ,就好像它是java.lang.String实例上的字段一样。 Presumably you already have an instance of SecureResource , so you'd want to call: 大概您已经有一个SecureResource实例,因此您要调用:

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 .) (其中resource是对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. 您的代码在有严格的安全管理器的情况下将无法使用,面对实现的更改它会变得很脆弱,并且通常表明您正在尝试执行未针对该类设计的操作。

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

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