Reputation: 10280
I have a Java backend system that processes JSON information sent by a client. In order to determine what kind of processing should take place I use a field in the JSON called "type"
My backend system checks the "type" and executes specific Java code based on the type.
Instead of checking the type and executing the code that is hard coded into my Java class, I'm interested in exploring ways to run code from an external database. This way when I want to create more "types" I can simply add the ways of processing each type in a database rather than having to hard code a new check or class into my Java file and recompiling/deploying.
I've read this StackOverFlow post: Convert String to Code , but as the comments point out, there is a significant risk associated with just having arbitrary code ran.
Ideally, I'd like to have some Java method that is loaded externally that has a parameter for the JSON data, and then it does it's own checks and processing and returns a value.
Is there any safe and (somewhat) easy way to do this? Perhaps parsing string as java code isn't the right idea (maybe doing some external class loading would be smarter), but I wanted to ask if anyone has any ideas regarding ways to do this.
Upvotes: 0
Views: 195
Reputation: 32407
Ah, good old soft coding. I recommend you have a read of http://thedailywtf.com/Articles/Soft_Coding.aspx before going down this path.
If you insist on being able to modify the code at run time, check out OSGi. Instead of a database, you would have dynamic bundles that could be modified to reflect updated code.
Upvotes: 1
Reputation: 10020
If the code to be executed is only short (a one-liner or so), you could just have it stored in your program's configuration as key-value pairs, where key is the type found in JSON messages and value is the code to be executed. Compile the one-liners with Groovy and there you are.
If the code to be executed is longer, define an interface and create a number of implementations. In the configuration, associate types from JSON with classes. Instantiating a class with known name is just Class.forName(...).newInstance()
plus error handling. This could also allow you to create plugins - simply put a new implementing class in your classpath, add entry in configuration and restart the app. You could probably do this with Spring and beans, but for a simple case doing it manually is probably easier and faster.
These solutions are safe since we assume malicious users can't change your configuration or JARs (otherwise you would already be in deep trouble).
Upvotes: 1