Accessing local variables in the main method via reflection

后端 未结 2 1255
离开以前
离开以前 2021-01-03 03:09

Just having a play around with Java reflection and I think I\'m getting the hang of it for the most part. I understand from this question/answer that, for the most part, I\'

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-03 03:28

    Since main is static, is it possible to access instanceOfB in order to access the value of _nonStaticInt?

    "No." Local variables (being in a static method or not) cannot be accessed with the Java Reflection API. Reflection only works at the type level, not the byte-code level2.

    The stated understanding of the linked question is correct; reflection access of a non-static (instance) field logically requires an instance. That is, the issue then isn't about reflecting on the B type, the issue is about obtaining the B instance (which is assigned to a local variable) to reflect upon.

    To do this the B instance has to be "bled" somehow - e.g. assigned to a static field or passed as an argument to a method/constructor from main1 - so that it can be used with reflection later as the object who's instance members are to be accessed.

    The cleanest approach would probably be to pass the B instance down through the appropriate context (or "DI"), perhaps with the aide of IoC .. and maybe changing the type to avoid the use of reflection entirely.


    1 Another possible way to "bleed" the B instance is to attach a debugger and inspect/use the local variable within the main methods executing frame - but this sounds like trying to swat a fly with a club.

    2 Even tooling like BCEL/ASM wouldn't immediately help during the execution of the main method. Rather it would be used to deconstruct the method, add in the required hooks/code to "bleed" or use the instance created, and then construct a modified method to execute.

提交回复
热议问题