简体   繁体   中英

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).

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

I suggested Reflection as a solution but what you want is an approach to tackle your problem and not a technical solution for it.

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. 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.

Most naively, you can disassemble the class with javap and grep the output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM