java 使用 Spring ReflectionUtils

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16954788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:31:04  来源:igfitidea点击:

Using Spring ReflectionUtils

javaspring

提问by Lav

I don't fullyunderstand the last linein following piece of code

我不完全理解以下代码中的最后一行

 Field init = ReflectionUtils.findField(ABCClass.class, "init");
 ReflectionUtils.makeAccessible(init);
 init.set(null, false);

What i do understand that its setting the AbcClass.init=false using Reflection API. What i dont understand is why we dont have a setter like

我所理解的是它使用反射 API 设置 AbcClass.init=false。我不明白的是为什么我们没有像这样的二传手

set(Object value) // looks logical as we have reference to field , we can simply set the value

but instead we have Something like

但我们有类似的东西

set(Object obj,Object value) 

I went through the api doc http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Field.html#set(java.lang.Object, java.lang.Object) it says

我浏览了 api doc http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Field.html#set(java.lang.Object, java.lang.Object) 它说

If the underlying field is static, the obj argument is ignored; it may be null.

Otherwise the underlying field is an instance field. If the specified object argument is null, the method throws a NullPointerException.

如果基础字段是静态的,则忽略 obj 参数;它可能为空。

否则,基础字段是实例字段。如果指定的对象参数为 null,则该方法将引发 NullPointerException。

But in my test case its not throwing any null pointer exception

但是在我的测试用例中它没有抛出任何空指针异常

I tried googling around for more example usage of this api , didnt find any useful example , may be some more examples can help me understand better.

我试着在谷歌上搜索这个 api 的更多示例用法,没有找到任何有用的示例,可能更多的示例可以帮助我更好地理解。

回答by Aleksander Blomsk?ld

initis a static method on ABCClass. As the documentation says, if the underlying field is static, the first argument is ignored; it may be null.

init是 ABCClass 上的静态方法。正如文档所说,如果基础字段是静态的,则第一个参数将被忽略;它可能为空。

回答by Thihara

The reason I can imagine is this.

我能想象的原因是这个。

The way you are getting that field it doesn't know the instance it belongs to. In static fields that is fine since static makes the field belong to the class and can exist independently without an instantiated object.

您获取该字段的方式不知道它所属的实例。在静态字段中很好,因为静态使字段属于类并且可以独立存在而无需实例化对象。

But a non static field will need an instantiated object to exist. Resulting in the set method requiring to know what that instance is.

但是非静态字段需要实例化对象才能存在。导致 set 方法需要知道该实例是什么。