com.github.jackpanz.spring.initialization.ConstantsInstantiation Maven / Gradle / Ivy
The newest version!
package com.github.jackpanz.spring.initialization;
import org.apache.commons.lang3.BooleanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
public class ConstantsInstantiation {
private static final Logger logger = LoggerFactory.getLogger(ConstantsInstantiation.class);
public static void readConstant(Class clazz,String propertiePath) {
List numbers = Arrays.asList(new Class[]{
byte.class, short.class, int.class, long.class, float.class, double.class
});
try (InputStreamReader inputStream = new InputStreamReader(ConstantsInstantiation.class.getResourceAsStream(propertiePath), "UTF-8")) {
Properties properties = new Properties();
properties.load(inputStream);
properties.keys();
Object constantsConfigurer = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
String name = fields[i].getName();
try {
String value = (String) properties.get(name);
if (value != null) {
if (fields[i].getType() == String.class) {
fields[i].set(constantsConfigurer, value);
} else if (fields[i].getType() == boolean.class) {
fields[i].set(constantsConfigurer, BooleanUtils.toBoolean(value));
} else if (numbers.contains(fields[i].getType())) {
String methodName = "to" + fields[i].getType().getName().substring(0, 1).toUpperCase() + fields[i].getType().getName().substring(1);
Class> threadClazz = Class.forName("org.apache.commons.lang3.math.NumberUtils");
Method method = threadClazz.getMethod(methodName, String.class);
Object object = method.invoke(null, value);
fields[i].set(constantsConfigurer, object);
}
logger.info(clazz.getCanonicalName() + " " + name + " = " + fields[i].get(constantsConfigurer));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy