Friday 20 May 2016

Java: Owner: Type conversion of custom types


Simplest way is to define your business object with a public constructor which takes a single parameter of type java.lang.String.
public class Employee {
  private String id;
  private String name;

  public Employee(String id) {
    this.id = id;
  }

  public String getId() {
    return id;
  }

  public void setId(String 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 org.aeonbits.owner.Config;

public interface ProjectConfig extends Config {

  @Key("first_name")
  @DefaultValue("Krishna")
  String firstName();

  @DefaultValue("5.4")
  float height();

  Employee employee();

}

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("height", "5.8");
    properties1.put("employee", "E432156");

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

    System.out.println(cfg.firstName());
    System.out.println(cfg.height());
    System.out.println(cfg.employee());
  }
}


Output
Krishna
5.8
Employee [id=E432156, name=null]




Previous                                                 Next                                                 Home

No comments:

Post a Comment