Accessing local variables in the main method via reflection

后端 未结 2 1253
离开以前
离开以前 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:22

    Yes, you can get the value of _nonStaticInt in that same way:

    B instanceOfB = new B();
    
    Field f = B.class.getDeclaredField("_nonStaticInt");
    
    // Because the variable is private you need this:
    f.setAccessible(true);
    
    Object content = f.get(instanceOfB);
    System.out.println(content);
    

    The value will be 0, that is the default value for an int.

提交回复
热议问题