I have class structure to read the data from resource bundle (property files).
import java.util.Locale;
import java.util.Objects;
import java.util.ResourceBundle;
/**
* The class will be used to read the resource bundle to achieve localization
* and internationalization
*
*/
public class ResourceBundleReader {
private String resourceBundle = null;
/**
* Constructor of the class
*
* @param resourceBundle
* @throws NullPointerException
* if resourceBundle is null
*/
public ResourceBundleReader(final String resourceBundle) {
Objects.requireNonNull(resourceBundle);
this.resourceBundle = resourceBundle;
}
/**
* Return message by input key for default locale
*
* @param key
* @return
*/
public String getMessage(final String key) {
return getMessage(key, Locale.getDefault());
}
/**
* Return message by input key for input locale locale
*
* @param key
* @return
*/
public String getMessage(final String key, final Locale locale) {
final ResourceBundle mybundle = ResourceBundle.getBundle(resourceBundle, locale);
return mybundle.getString(key);
}
}
As there are multiple type of resource bundles, I have created individual implementation for that. For example below two:
Exception Message:
public final class ExceptionMessageResolver {
private static final String EXCEPTION_MESSAGES_RESOURCE = "exceptionmessages"; //$NON-NLS-1$
private static final ResourceBundleReader RESOURCE_BUNDLE_READER = new ResourceBundleReader(
EXCEPTION_MESSAGES_RESOURCE);
/**
* Private constructor to prevent instantiation Constructor of the class
*/
private ExceptionMessageResolver() {
super();
}
/**
* return exception message by default locale
*
* @param key
* @return
*/
public static String getMessage(final String key) {
return getMessage(key, Locale.getDefault());
}
/**
* Return exception message for input locale
*
* @param key
* @param locale
* @return
*/
public static String getMessage(final String key, final Locale locale) {
return RESOURCE_BUNDLE_READER.getMessage(key, locale);
}
}
Label Messages:
public final class ResourceLabelResolver {
private static final String LABEL_RESOURCE = "resourcelabels"; //$NON-NLS-1$
private static final ResourceBundleReader RESOURCE_BUNDLE_READER = new ResourceBundleReader(LABEL_RESOURCE);
/**
* Private constructor to prevent instantiation Constructor of the class
*/
private ResourceLabelResolver() {
super();
}
/**
* return label message by default locale
*
* @param key
* @return
*/
public static String getMessage(final String key) {
return getMessage(key, Locale.getDefault());
}
/**
* Return label message for input locale
*
* @param key
* @param locale
* @return
*/
public static String getMessage(final String key, final Locale locale) {
return RESOURCE_BUNDLE_READER.getMessage(key, locale);
}
}
Is there any more elegant way for this? Or any way to create abase class for my two readers to prevent duplicate methods in code?