通过 ASM Java 字节码访问外部类的私有字段时出现 java.lang.IllegalAccessError
在反射中,可以通过 getDeclaredField() 和 setAccessible(true) 访问私有字段。如何通过Objectweb ASM字节码API访问外部类的私有字段? 我设置从类似的东西获取私有字段,通过
Field current = sourceObject.getDeclaredField(privateFieldName);
Field.setAccessible(true);
Type sourceType = Type.getType(sourceObject.getClass());
mv.visitFieldInsn(Opcodes.GETFIELD,
sourceType.getInternalName(),
privateFieldname,
Type.getDescriptor(current.getType()));
当执行字节代码并获取私有字段时,我总是收到错误“java.lang.IllegalAccessError”
任何线索?谢谢一包,
in reflection, the private field can be access via getDeclaredField() and setAccessible(true). How to access the private field of a outside class via Objectweb ASM bytecode API?
I set to get the private field from something like, via
Field current = sourceObject.getDeclaredField(privateFieldName);
Field.setAccessible(true);
Type sourceType = Type.getType(sourceObject.getClass());
mv.visitFieldInsn(Opcodes.GETFIELD,
sourceType.getInternalName(),
privateFieldname,
Type.getDescriptor(current.getType()));
When the byte code is executed and to get the private field, I always got an error "java.lang.IllegalAccessError "
Any clue? Thanks a bundle,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能那样做。
setAccessible(true)
只会影响程序当前执行中的当前字段引用(也就是说,它不会影响最终修改程序的执行) 。要在运行修改后的程序时访问私有字段,您基本上必须将相应的反射步骤嵌入到程序中。
要访问存储在局部变量
varId
中的某个对象的私有字段YourClass.thePrivatefield
,您可以执行以下操作:如果您尝试访问的字段是 cobe 基础的一部分如果您要重写,您显然也可以使用 ACC_PUBLIC 代替 ACC_PRIVATE 来将该字段公开。
You can't do it like that. The
setAccessible(true)
will only affect the current field-reference in the current execution of your program (that is, it will not affect the execution of the resulting modified program).To access a private field when running your modified program, you basically have to embed the corresponding reflection-steps into the program.
To access a private field
YourClass.thePrivatefield
of some object stored in local variablevarId
you do something likeIf the field you're trying to make accessible is part of the cobe base that your'e rewriting, you could obviously also make that field public by using
ACC_PUBLIC
instead ofACC_PRIVATE
.实际问题是您无法合法访问这些变量。这是因为 JVM 在 Java 拥有内部类之前定义了其访问规则,因此 javac 为在 JVM 中无法合法访问但在 Java 中可以合法访问的字段创建合成访问器。例如,
然后我们可以使用
javap
来反编译生成的类。请注意在
Sample
中生成并从Sample.Inner
使用的access$000(Sample)
方法。遗憾的是,您的选择是要么The actual problem is that you cannot legally access those variables. This is because the JVM defined its access rules before Java had inner classes, so javac creates synthetic accessors for fields that it cannot legally access in the JVM but can in Java. For example,
Then we can use
javap
to decompile the generated classes.Notice the
access$000(Sample)
method that got generated inSample
and used fromSample.Inner
. Sadly, your options are to either