views:

65

answers:

4

Is it possible to set a default behaviour for custom (non-native) methods/functions in Java?

For example, I would like to change the default "Function" to do a System.out.println("message") whenever called.

So, when a custom method/function is being created:

public String testMethod()
{
   //custom code
}

it should execute the newly added default behaviour (in this case the system output), before the custom code is run.

Even if this would be a bad excercise, is it possible? Maybe by extending the function class or something?

+2  A: 

It sounds like you want either aspect-oriented programming (e.g., AspectJ) or byte-code weaving (e.g., ASM or cglib).

bkail
Or Apache's Byte-Code Engeneering Library (BCEL).
Pindatjuh
+2  A: 

Hello,

Maybe, you should look at java.reflect.Proxy.But it requires that you create one proxy per class for which you want to monitor method calls.

An example :

    @SuppressWarnings("unchecked")
  public static <T> List<T> traceList(final List<T> list) {
    return (List<T>)Proxy.newProxyInstance(
      ProxyTest.class.getClassLoader(),
      new Class<?>[]{List.class}, 
      new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable {
          System.out.println("enter "+method);
          try {
           return method.invoke(list,args);
          } finally {
            System.out.println("exit "+method);
          }
        }
      });
  }
jinh
Thank you for editing Steven ;) !
jinh
+3  A: 

One way is using Aspect-oriented programming (AOP) for Java: Aspect/J. For what you want, AOP would let you inject code in your program at specific points, e.g. having specified methods execute some println code upon entering or exiting the method. [AOP has a much larger purpose than this simple use for printing debug statements, but I'm trying to stay on target for answering the question.]

This article (possibly somewhat dated) shows an example similar to what you want:

http://www.developer.com/java/other/article.php/3109831/Simplify-your-logging-with-AspectJ.htm

Bert F
Funny, I was actually trying to setup "Aspect Oriented Programming". I did not know it already existed! Thanks for the link. My goal is to create the core of a game, and then add features one by one using AOP. This will allow me to individually implement and then enable/disable features to see their effects on the project.
Tom
@Tom - glad to help - now that you have a name for it, I would think you should be able to find a ton of material online and in print about Aspect-Oriented Programming to dive into - basics, when/how to use it, best practices, etc.
Bert F
A: 

If you only need to do this for your own classes and not for classes from the Java library or that you get from someone else, then this is what Object-Oriented Programming is all about. Create your top level class, put this function in it, and then derive any other classes from there.

Jay