Home > Mobile >  Is there a way of parsing strings to class types from YAML?
Is there a way of parsing strings to class types from YAML?

Time:01-27

I was wondering if there is any way of loading a YAML configuration like this:

classes:
  a: A.class
  b: B.class

in such a way that A.class and B.class can later be retrieved as Class type (something similar to Map<String, Class>

Update #1

I'm using Spring Boot to load configuration in this class:

@Getter
@Setter
@Configuration
@ConfigurationProperties
public class ClassesConfig {

    private Map<String, Class<?>> classes;

}

I could do something like this, but I don't actually know how to achieve that while maintaining the use of this class...

CodePudding user response:

This should work:

@Component
@ConfigurationPropertiesBinding
public class ClassConverter implements Converter<String, Class<?>> {

    @Override
    public Class<?> convert(String from) {
        return Class.forName(from);
    }
}

Tweak it according to your needs; for example, if you want the .class suffix in the YAML file, remove that from the string from because it is not part of the class name.

Mind that you need to give the fully qualified name of the class. So if A and B are in a package, you need to give that package as prefix.

  • Related