修改字节码使方法返回 true
我的类文件有一个这样的方法:
public boolean validate(String str) {}
这个验证方法中有很多代码,但我只想让它始终返回 true 或 false。有人可以指出如何修改类文件来实现此目的吗?
I have class file has a method like this:
public boolean validate(String str) {}
There're lots of codes inside this validate method, but I only want to make it always return true or false. Can someone point me out how to modify a class file to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
规则覆盖 rtn
福级
方法验证
如果为真
请返回 true
ENDRULE
http://www.jboss.org/byteman
RULE override rtn
CLASS Foo
METHOD validate
IF true
DO RETURN true
ENDRULE
http://www.jboss.org/byteman
您是否试图对这段代码进行单元测试并强制给出答案而不关心条件?如果是这种情况,那么您正在寻找“Mocking”框架。在Java中,我可以想到 Mockito 和 EasyMock 就在我的脑海中。
相关地,您可以使用 PowerMock(与上述任一模拟框架配合使用)动态地更改类(例如
final
类/方法、static
方法,甚至private
类片段)。 PowerMock实际上可以在必要时更改字节码。检查其类加载文件夹。我从未考虑过它,但可能可以在非测试代码中使用它们中的任何一个,但它们可能需要欺骗以避免 JUnit 依赖项(例如 JUnit Runner)。再说一遍,我从来没有考虑过这个问题,所以我从来没有考虑过其中的含义。
至少,您可以通过 PowerMockito 来了解它们如何更改字节码。
如果您只想进行单元测试,那么这非常简单,您可能不需要担心字节代码。
测试(将 Mockito 与 JUnit 4 结合使用(删除 JUnit 3 的
@Test
属性)):Are you trying to unit test this code and force an answer without caring about the conditions? If that is the case, then you are looking for "Mocking" frameworks. In Java, I can think of Mockito and EasyMock off of the top of my head.
Relatedly, you can use PowerMock (works in tandem with either of the above Mocking frameworks) to dynamically change classes (such as
final
classes/methods,static
methods, and evenprivate
pieces of classes). PowerMock actually can change the byte code when necessary. Check under its classloading folders.I've never considered it, but it might be possible to use any of them within non-test code, but they may require finagling to avoid JUnit dependencies (such as JUnit Runner). Again, I have never thought about it, so I never thought through the implications.
At the very least, you can probably look through PowerMockito to see how they change the byte code.
If you just want to unit test, then it's extremely easy and you probably don't need to worry about the byte code.
Test (using Mockito with JUnit 4 (drop the
@Test
attribute for JUnit 3)):根据提供的方法签名,它只能返回 true 或 false。
您能否创建一个包装类,将调用委托给原始类并覆盖您所需的行为,而不是尝试操作字节码?
It can only return true or false, according to the method signature provided.
Can you make a wrapper class that delegates calls to the original and overrides the behaviour that you require, instead of trying to manipulate the bytecode?
修改字节码的最简单方法是反编译类或获取源代码的副本。更改代码并编译。将新版本放在类路径的早期位置或替换 jar 中的原始版本。这样你就改变了方法。
您可以在运行时更改它,但这要困难 100 倍。 ;)
The simplest way to modify the byte code is to decompile the class or get a copy of the source code. Change the code and compile it. Put the new version earlier in the classpath or replace the original in the jar. This way you have changed the method.
You can change it at runtime, but that is 100x harder. ;)