Saturday 21 May 2016

Java: Owner: Specify Custom converter


By implementing Converter interface, we can specify custom converter.

import java.lang.reflect.Method;

import org.aeonbits.owner.Converter;

public class EmployeeConverter implements Converter<Employee> {

  @Override
  public Employee convert(Method method, String input) {
    String[] split = input.split(";");

    int id = Integer.parseInt(split[0]);
    String name = split[1];

    Employee emp = new Employee();
    emp.setId(id);
    emp.setName(name);

    return emp;
  }

}

public class Employee {
  private int id;
  private String name;

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  @Override
  public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append("Employee [id=").append(id).append(", name=")
        .append(name).append("]");
    return builder.toString();
  }

}


import java.util.List;

import org.aeonbits.owner.Config;

public interface ProjectConfig extends Config {

  @DefaultValue("1;Hari Krishna Gurram")
  @ConverterClass(EmployeeConverter.class)
  Employee employee();

  @DefaultValue("1;Hari Krishna Gurram, 2;Senthil, 3;Rakesh")
  @ConverterClass(EmployeeConverter.class)
  List<Employee> employees();

}


import org.aeonbits.owner.ConfigFactory;
import java.util.*;

public class PropertyUtil {
  public static void main(String args[]) throws Exception {
    Map<String, String> properties1 = new HashMap<>();

    properties1.put("employee", "1;Prasob");
    properties1.put("employees", "1;Sandesh, 2;Desraj, 3;Srinath");

    ProjectConfig cfg = ConfigFactory.create(ProjectConfig.class,
        properties1);

    Employee emp = cfg.employee();
    List<Employee> emps = cfg.employees();

    System.out.println("----------------");
    System.out.println(emp);

    System.out.println("----------------");
    for (Employee employee : emps) {
      System.out.println(employee);
    }

  }
}


Output

----------------
Employee [id=1, name=Prasob]
----------------
Employee [id=1, name=Sandesh]
Employee [id=2, name=Desraj]
Employee [id=3, name=Srinath]




Previous                                                 Next                                                 Home

No comments:

Post a Comment