Five ‘s Weblog

October 8, 2007

Applying Java reflection to Ioc and AOP (2)

Filed under: Programming — by powerdream5 @ 3:30 am
Tags: , , ,

        Today, let’s continue the example of applying java reflection to AOP(Aspect-oriented programming). Because the core of AOP is proxy, I want to make a brief description of it firstly.
        The two important tasks of proxy are interface implementation and delegation. Interface implementation means the proxy class need to implement all the interfaces the target class implements, and delegation means the proxy will catch all the calls to the target class, so that it is easy to add functions before or after the target methods.

blog.JPG

           java.lang.reflect.Proxy helps us create a proxy of the target class dynamically, and java.lang.reflect.InvocationHandler interface will allow the proxy class delegate the calls to the target class.
          The following example shows how to use proxy to realize the function of logging. By extracting the function of logging from the method, we can concentrate our method in business logic.

//TargetInterface.java
//Define the interface the target class implements

public interface TargetInterface{
     public void print();
}

//TargetImplementation.java
//The class implements the interface

public class TargetImplementation implements TargetInterface{
    public void print(){
          System.out.println(“print method”);
    }
}

//ProxyTarget.java
//Create the proxy class and delegate the calls to the target class

import java.lang.reflect.*;
public class ProxyTarget implements InvocationHandler{
      public static Object createProxy(Object obj){
            //creat the proxy class according the instance of the target class                 
            return Proxy.newProxyInstance(obj.getClass().getClassLoader(),
                                                                           obj.getClass().getInterfaces(),
                                                                           new ProxyTarget(obj));
       }

        private Object target;
        private ProxyTarget(Object target)
        {
                this.target = target;
         }
 
        //Implements the method of InvocationHandler interface
        //This method will catch all the calls to the target class
        //and redispatch them       

        public Object invoke(Object proxy, Method method, Object[] args)
        {
                 Object result = null;
                 try{
                        //add function before redispatching
                        System.out.println(“Before “+method.getName());
                        //redispatch the call
                        result = method.invoke(target,args);
                        //add function after redispatching
                        System.out.println(“After “+method.getName());
                 }catch(Exception e){
                        System.out.println(e.getMessage());
                 }
                 return result;
          }
}

//TestProxyTarget.java
//the test class

public class TestProxyTarget{
        public static void main(String[] args){
                 TargetInterface t = (TargetInterface)ProxyTarget.createProxy(
                                                                                   new TargetImplementation());
                 //this will call the invoke method of the ProxyTarget class automatically and transparently 
                 t.print();
        }
}

The running result of the TestProxyTarget is:

blogcmd.JPG

         After reading the examples, I hope you can have some basic ideas of Ioc and Aop, and figure out the relationship between java reflection and Ioc and AOP. Of course, if you want to learn more, please search more materials about them.

xiaoran.jpg

 

October 7, 2007

Applying Java reflection to Ioc and AOP (1)

Filed under: Programming — by powerdream5 @ 1:10 am
Tags: , ,

reflection

         JDK1.5 has introduced many useful features, including annotation and reflection. And now, IOC(Inversion of Control) and AOP(Aspect-oriented programming) would be the most popular words in the J2EE field. Today, I am not going to explain what is IOC and what is AOP. I just want to show two examples to present the technology of java reflection plays an important role in IOC and AOP.

        The first example would be a little bit different from the the concept of IOC, but the common thing is that both load the calss dynamically. In this example, I use properties file as the configuration file, but in a real application, we mostly use xml files.

//InjectionInterface.java 
//Firstly, we define a interface

public interface InjectionInterface{
       public void print();
}

//InjectionClass_1.java
//implements the InjectionInterface
public class InjectionClass_1 implements InjectionInterface{
       public void print(){
               //print out the name of the class the object belongs to
               System.out.println(“the print method of class InjectionClass_1”);
       }
}

//InjectionClass_2java
//implements the InjectionInterface

public class InjectionClass_2 implements InjectionInterface{
      public void print(){
              //print out the name of the class the object belongs to
              System.out.println(“the print method of class InjectionClass_2”);
     }
}

//Ioc.java-the testing class 
import java.util.Properties;
import java.io.*;

public class Ioc{
      private InjectionInterface injectionClass;

      //using setter injection
     public void setInjectionClass(InjectionInterface injectionClass)
    {
            this.injectionClass = injectionClass;
    } 

    public void print()
   {
            injectionClass.print();
    }

    public static void main(String[] args)
   {
            try{
                  Properties props = new Properties();
                  props.load(new FileInputStream(“injection.properties”));
                  String classname = props.getProperty(“iocclass”);
                 //dynamically load the class according to the class name
                  Class cls = Class.forName(classname);
                  Ioc ioc = new Ioc();
                 //get an instance of the loaded class
                  ioc.setInjectionClass((InjectionInterface)cls.newInstance());
                  ioc.print();
            }catch(Exception e){
                    e.printStackTrace();
            }
        }
}

//injection.properties – the properties file
iocclass=InjectionClass_1

The running result of the program is: the print method of class InjectionClass_1

Now, you can change the properties file: iocclass=InjectionClass_2. you don’t need to compile the java files again, and just run the class directly. you can see the result would be different.

ioc.JPG

        After reading the example, I hope you have a better understanding of IOC. And tomorrow, I will show the example about using the technology of reflection in AOP.

Create a free website or blog at WordPress.com.