Skip to content

Naming Strategies

Mazen Kotb edited this page Jul 5, 2016 · 2 revisions

Naming strategies are a method ConfigAPI uses to change java field names to match YAML conventions. By default, the API assumes the fields are using the camel case convention, supporting both upper and lower conventions (thisWorks, AsDoesThis). Naming strategies are under the internal package, however if one wanted to they could extensify this to their own wants/needs as explained in Writing your Own Strategy.

Built-in Strategies

ConfigAPI has the following strategies:

  • Camel case (id: camelcase) = fooBar || 'FooBar' -> foo-bar
  • Underscore (id: underscore) = foo_bar || 'FOO_BAR' -> foo-bar
  • Dummy/None (id: dummy and null) = fOoBaR -> fOoBaR (no modifications)

To access the strategies, you can call NamingStrategies.from(String) and it will return the corresponding strategy, or null if there is none.

Selecting a Strategy

Once you've created your ConfigFactory, you can set the naming strategy it will use by using the ConfigFactory#setPreferredStrategy(NamingStrategy) method, from thereon it will load and save assuming the naming strategy.

Note: If you wish to convert a file to a new strategy, you first must have the old strategy set when calling the ConfigFactory#fromFile(String, Class<T>) method, then afterwards change to the new strategy when calling the save method.

Writing your own Strategy

If you're a special snowflake and use a very specific convention in your project, you can write your own strategy and register it accordingly for the API to use. If you believe there is a major convention missing from this project, feel free to create an issue or create a pull request with the strategy for it added.

Writing a strategy is simple, all you need to do is implement the NamingStrategy class, like the following:

public class MyStrategy implements NamingStrategy {
    @Override
    public String rename(String input) {
        // input is given as the Java field name, the objective of this
        // method is to rename input to the name that will be used in 
        // the config
    }
}

Once that is done, you will need to register it in NamingStrategies holder by calling the insert method with it's id. Then finally, set the strategy as the one you will use in your config factory like the following:

NamingStrategies.insert("mystrategy", new MyStrategy());
configFactory.setPreferredStrategy(NamingStrategies.from("mystrategy"));

and that's it!

Clone this wiki locally