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).
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.
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
PowerMockito
and throw exceptions when a bad method is called, but that seems somewhat unconvenientaspects
to any class/methodString.lastIndexOf()
, can be implemented in pure Java without delegating to other Java library methods, doing this would be entirely pointless. Doubly so when you consider that open source implementations are available, so the restriction could be circumvented for almost no effort.