是否可以重写 Random 类的 Java 实现?
在 C++ 中使用 Windows Detours ,我发现可以蹦床函数调用,以便您可以拦截 Windows 基本功能并返回自定义结果集,而无需修改原始函数调用。
我想知道是否有任何方法可以覆盖 Java 随机化调用,以便我可以实现自己的结果集。在上一个问题中,我问是否有任何方法可以让 C# 模仿 Java 随机化函数 。作为一种可能的解决方案,在不扰乱其他问题的情况下,我想知道是否有人有实施“绕道式”解决方案的经验。
Using Windows Detours in C++, I've seen that it is possible to trampoline function calls so that you may intercept windows base functionality and return custom resultsets, without modifying the original function call.
I was wondering if there is any way to override a Java Randomization call so that I may implement my own result set. In a previous question, I asked if there was any way to make C# mimic the Java randomization function. As a possible solution, without cluttering up the other question, I wanted to know if anyone has had any experience in implementing a "detoured-like" solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您负责实例化 java.util.Random 对象,那么您可以子类化 java.util.Random 并实例化您自己的类。如果您无法更改的其他代码负责实例化,那么您显然不能使用自己的子类。我希望这不是您的情况的选择。
另一种选择是在类加载时更改实现。基本上,您重写 java.util.Random 的字节码以执行默认情况下执行的操作以外的操作。这样做的缺点是,它将影响 java.util.Random 的所有实例,而不仅仅是您可能想要更改的一个实例。不过,大多数代码不依赖于 RNG 的实现细节,因此这可能不是问题。
Javassist 是一个相当不错的字节代码库。它将允许您在类加载时重写字节代码,因此您可以通过调用您自己的实现所需 RNG 算法的类来替换生成随机数的方法主体。
您可以编写一个简单的类文件处理器,它将为 java.util.Random 类运行。代码可能是这样的:
If you are responsible for instantiating a java.util.Random object, then you can subclass java.util.Random and instantiate your own class instead. If some other code, that you cannot change, is responsible for the instantiation, then you obviously cannot use your own subclass. I expect this is not an option in your case.
Another alternative is to change the implementation at class load time. Basically you rewrite the bytecode of java.util.Random to do something else than what it does by default. The downside of this is that it will affect all instances of java.util.Random, not just the one instance that you might want to change. Then again, most code do not rely on the implementation details of the RNG so this probably isn't an issue.
Javassist is quite a nice byte code library. It'll allow you to rewrite byte code at class load time, so you could, e.g. replace the body of the method that produces the random number with a call to your own class that implements the RNG algorithm that you need.
You could write a simple class file processor that will be run for the java.util.Random class. The code might be something like this: