[英]How do I prevent the use of arbitrary methods, for example String.lastIndexOf()
I have a scenario where I want to run code that I don't control. 我有一个场景,我想运行我无法控制的代码。 I want to prevent arbitrary standard JDK methods from being used in that code (for example, I want to prevent the usage of the lastIndexOf() method on any String objects).
我想阻止在该代码中使用任意标准JDK方法(例如,我想阻止在任何String对象上使用lastIndexOf()方法)。
If a forbidden method is used, it should result in a run time exception. 如果使用禁用方法,则应导致运行时异常。
I suspect this might be possible with a custom class loader but I'm not sure how to approach this. 我怀疑这可能是自定义类加载器,但我不知道如何处理这个问题。 Part of the problem I ran into is that String is a final class that can't be extended.
我遇到的部分问题是String是一个无法扩展的最终类。
Example: 例:
//I control this code
int result = SomeClass.method("foo") //I don't control SomeClass
//A valid implementation of SomeClass.method()
int method(String in) {return 1;}
//An invalid implementation of SomeClass.method()
int method(String in) {return in.lastIndexOf("o");}
//the above should throw an error at run time when called from my code
I suggested Reflection as a solution but what you want is an approach to tackle your problem and not a technical solution for it. 我建议将Reflection作为一种解决方案,但你想要的是一种解决问题的方法,而不是技术解决方案。
The domain of your problem can be much bigger than what we are discussing here. 你问题的领域可能比我们在这里讨论的要大得多。
I remember writing a custom findbugs detector that looked for specific method calls. 我记得写过一个自定义的findbugs探测器,它寻找特定的方法调用。 In my case it analysed it's parameters as well, but it looks your case is a bit simpler.
在我的情况下,它也分析了它的参数,但看起来你的情况有点简单。
Alternatively, you can use ASM library. 或者,您可以使用ASM库。
Most naively, you can disassemble the class with javap and grep the output. 最天真的是,您可以使用javap和grep输出来反汇编类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.