开发者

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

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 adde开发者_如何学JAVAd 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?


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


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


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);
          }
        }
      });
  }


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜