Can I call make runtime decided method calls in Java?
Posted
by
Catalin Marin
on Stack Overflow
See other posts from Stack Overflow
or by Catalin Marin
Published on 2011-01-14T09:34:04Z
Indexed on
2011/01/14
9:53 UTC
Read the original article
Hit count: 295
I know there is an invoke function that does the stuff, I am overall interested in the "correctness" of using such a behavior. My issue is this: I have a Service Object witch contains methods which I consider services. What I want to do is alter the behavior of those services without later intrusion. For example:
class MyService {
public ServiceResponse ServeMeDonuts() {
do stuff...
return new ServiceResponse();
}
after 2 months I find out that I need to offer the same service to a new client app and I also need to do certain extra stuff like setting a flag, or make or updating certain data, or encode the response differently. What I can do is pop it up and throw down some IFs. In my opinion this is not good as it means interaction with tested code and may result in un wanted behaviour for the previous service clients.
So I come and add something to my registry telling the system that the "NewClient" has a different behavior. So I'll do something like this:
public interface Behavior {
public void preExecute();
public void postExecute();
}
public class BehaviorOfMyService implements Behavior{
String method;
String clientType;
public void BehaviorOfMyService(String method,String clientType) {
this.method = method;
this.clientType = clientType;
}
public void preExecute() {
Method preCall = this.getClass().getMethod("pre" + this.method + this.clientType);
if(preCall != null) {
return preCall.invoke();
}
return false;
}
...same for postExecute();
public void preServeMeDonutsNewClient() {
do the stuff...
}
}
when the system will do something like this
if(registrySaysThereIs different behavior set for this ServiceObject) {
Class toBeCalled = Class.forName("BehaviorOf" + usedServiceObjectName);
Object instance = toBeCalled.getConstructor().newInstance(method,client);
instance.preExecute();
....call the service...
instance.postExecute();
....
}
I am not particularly interested in correctness of code as in correctness of thinking and approach. Actually I have to do this in PHP, witch I see as a kind of Pop music of programming which I have to "sing" for commercial reasons, even though I play POP I really want to sing by the book, so putting aside my more or less inspired analogy I really want to know your opinion on this matter for it's practical necessity and technical approach.
Thanks
© Stack Overflow or respective owner