I'm looking to avoid having a ridiculously large switch statement, so instead I've created this method:
private static Map<String, Constructor<?>> constructorCache = new ConcurrentHashMap<>();
public static Object instantiate(String path, Object... params) {
try {
Constructor<?> cons = null;
if(constructorCache.containsKey(path)) {
cons = constructorCache.get(path);
}
else {
Class<?>[]clazzes = new Class<?>[params.length];
for(int a = 0; a != params.length; a++)
clazzes[a] = params[a].getClass();
Class<?> clazz = Class.forName(path);
cons = clazz.getConstructor(clazzes);
}
return cons.newInstance(params);
} catch (Exception e) {
throw new RuntimeException("Error while instantiating " + path + " Stacktrace: " + e.getStackTrace());
}
}
Is this bad practice, especially for performance-critical code?
Aucun commentaire:
Enregistrer un commentaire