Saturday, May 11, 2013


To convert domain (POJO) object to Model (POJO) object

We can use spring converter but in that we need to create our own converter setting all the values.
So what required is i just need to put annotation on my domain and model objects and they should be mapped to each other. So instead of modelObj.setXXX(domainObj.getXXX) i want to use annotation.

So first I create a custom annotation:
Mapper.java
package main;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(value = ElementType.METHOD)
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Mapper {
       String value();
}

My model:
Model.java
package main;

public class Model {
       private String firstname;
       private String lastName;
       private String age;
       private String place;
      
       public String getFirstname() {
              return firstname;
       }
      
       public String getLastName() {
              return lastName;
       }
       @Mapper(value="lastName")
       public void setLastName(String lastName) {
              this.lastName = lastName;
       }
       public String getAge() {
              return age;
       }

       public String getPlace() {
              return place;
       }
      
       public void setPlace(String place) {
              this.place = place;
       }
       @Mapper(value="firstname")
       public void setFirstname(String firstname) {
              this.firstname = firstname;
       }
       @Mapper(value="age")
       public void setAge(String age) {
              this.age = age;
       }
}

My Domain:
Domain.java:
package main;

public class Domain {
       private String firstname;
       private String lastName;
       private int age;
      
       @Mapper(value="age")
       public int getAge() {
              return age;
       }
       @Mapper(value="firstname")
       public String getFirstname() {
              return firstname;
       }
       public void setFirstname(String firstname) {
              this.firstname = firstname;
       }
       @Mapper(value="lastName")
       public String getLastName() {
              return lastName;
       }
       public void setLastName(String lastName) {
              this.lastName = lastName;
       }

       public void setAge(int age) {
              this.age = age;
       }

}

My Main class that also contains the convert method:
Main.java
package main;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class Main {

    public Object convert(Object source, Object target) {
       Object result = null;
        try {

              Class<? extends Object> myclass = source.getClass();
              Class<? extends Object> targetClass = target.getClass();
            //Use reflection to list methods and invoke them
            Method[] sourceMethods = myclass.getMethods();
            List<Method> methods = new ArrayList<>();
            Method[] tempTargetMethods = targetClass.getMethods();
            List<Method> targetMethods = new ArrayList<>();
            for(Method method : sourceMethods) {
              if(method.getName().startsWith("get"))
                {
                     methods.add(method);
                }
            }
            for(Method method : tempTargetMethods) {
              if(method.getName().startsWith("set"))
                {
                     targetMethods.add(method);
                }
            }
            for (int i = 0; i < methods.size(); i++) {
               for (int j = 0; j < targetMethods.size(); j++) {
                Mapper sourceAnnotations = (Mapper)methods.get(i).getAnnotation(Mapper.class);
                if(sourceAnnotations != null ){
                    try{
                   
                    Annotation annotation = methods.get(i).getAnnotation(Mapper.class);
                    Annotation targetAnnotation = targetMethods.get(j).getAnnotation(Mapper.class);
                    if(annotation instanceof Mapper){
                           if((Mapper)annotation != null && (Mapper)targetAnnotation != null){
                               if(((Mapper)annotation).value().equalsIgnoreCase(((Mapper)targetAnnotation).value())) {
                                  result = targetMethods.get(j).invoke(target, new Object[] {  String.valueOf(methods.get(i).invoke(source)) });
                                  break;
                           }
                            }
                    }
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
            result = target;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
       Domain source = new Domain();
       Model target = new Model();
       source.setFirstname("sourceName");
       source.setAge(55);
       source.setLastName("sourceLastName");
       Main myMain = new Main();
       try{
              Model articleModel = (Model)myMain.convert(source, target);
              System.out.println("Main:"+articleModel.getLastName());
              System.out.println("Main:"+articleModel.getAge());
              System.out.println("Main:"+articleModel.getFirstname());
       }
       catch(Exception e) {
              e.printStackTrace();
       }
    }
}

No comments:

Post a Comment