Add a call method to each method in the class

I have a class with many methods:

public class A { public string method1() { return "method1"; } public string method2() { return "method2"; } public string method3() { return "method3"; } . . . public string methodN() { return "methodN"; } } 

I would like to add a call to doSomething () in each method, for example:

 public string methodi() { doSomething(); return "methodi"; } 

What is the best way to do this? Is there a suitable design template?

+7
source share
4 answers

Using AOP is already a good answer; that was my first idea.

I tried to find a good way to do this without AOP, although I came up with this idea (using the Decorator template):

 interface I { String method1(); String method2(); ... String methodN(); } class IDoSomethingDecorator implements I { private final I contents; private final Runnable commonAction; IDoSomethingDecorator(I decoratee, Runnable commonAction){ this.contents = decoratee; this.commonAction = commonAction; } String methodi() { this.commonAction().run(); return contents.methodi(); } } 

Then you can decorate the construct A (which implements I):

 I a = new IDoSomethingDecorator(new A(),doSomething); 

It’s basically not rocket science, but actually the result is more code than your first idea, but you can introduce a general action and you separate the additional action from class A. In addition, you can easily disable it or use it only in tests , eg.

+5
source

This is a typical use case for AOP (aspect-oriented programming). You define insertion points for method calls, and the AOP mechanism adds the correct code to the class file. This is often used when you want to add log instructions without cluttering the source files.

For java you can add aspectj library

For C # and .NET, see this blog . Sounds like a good starter.

+7
source

Why not have one function?

 public string methodi(int i) { doSomething(); return "method" + i.toString(); } 

Or you can write a function that takes a Func parameter and calls that function instead of your functions.

  public string Wrapper(Func<string> action) { doSomething(); return action(); } 

and call your functions from this function;

 string temp = Wrapper(method1); 
+1
source

You can use reflection.

 public String callMethod(int i) { doSomething(); java.lang.reflect.Method method; try { method = this.getClass().getMethod("method" + i); } catch (NoSuchMethodException e) { // ... } String retVal = null; try { retVal = method.invoke(); } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } return retVal; } 
0
source

All Articles