添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I don't fully understand the last line in 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

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

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.

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.

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.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.