Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a ConfigValue represents a object in Typesafe.Config

There is a interface in com.typesafe.config.Config:

Config withValue(String path, ConfigValue value);

Suppose now I want to save an object whose class is defined by myself into the Config, what should I do? The function ConfigValueFactory.fromAnyRef failed

My code looks like: val value = Resource(100) config.withValue("resource", ConfigValueFactory.fromAnyRef(value))

and here is the exception:

bug in method caller: not valid to create ConfigValue from: Resource(100) com.typesafe.config.ConfigException$BugOrBroken: bug in method caller: not valid to create ConfigValue from: Resource(100) at com.typesafe.config.impl.ConfigImpl.fromAnyRef(ConfigImpl.java:275)

like image 427
vincent_f Avatar asked Mar 18 '23 09:03

vincent_f


1 Answers

You cannot put arbitrary object into type safe config. If you'll go to fromAnyRef implementation you'll se that you can pass only primitives + maps. This works for me:

  val config = ConfigFactory.empty()

  case class Resource(i: Int)

  val value = 100
  //val value = Resource(100) // Failed 

  println(config.withValue("resource",
    ConfigValueFactory.fromAnyRef(value)))
like image 184
Eugene Zhulenev Avatar answered Mar 21 '23 02:03

Eugene Zhulenev