我有一个场景,我想运行我无法控制的代码。我想防止在该代码中使用任意标准 JDK 方法(例如,我想防止在任何 String 对象上使用 lastIndexOf() 方法)。
如果使用了禁止的方法,它应该会导致运行时异常。
我怀疑这可能通过自定义类加载器实现,但我不确定如何解决这个问题。我遇到的部分问题是 String 是一个不能扩展的最终类。
例子:
//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