Created
July 12, 2015 23:40
-
-
Save PaulBGD/9ba8bbb11252eb17a02d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import lombok.Data; | |
import org.apache.commons.lang3.Validate; | |
import java.lang.reflect.Constructor; | |
import java.lang.reflect.InvocationTargetException; | |
import java.util.HashMap; | |
/** | |
* @author PaulBGD | |
*/ | |
public class Implementations { | |
private static final HashMap<Class, Class> implementations = new HashMap<>(); | |
public static void registerImplementation(Class implementing, Class implementation) { | |
Validate.isTrue(!implementations.containsKey(implementation), "The implementation has already been registered"); | |
implementations.put(implementing, implementation); | |
} | |
public static <T> Class<? extends T> getImplementation(Class<T> clazz) { | |
return implementations.get(clazz); | |
} | |
public static <T> T getInstance(Class<? extends T> clazz, Parameter... parameters) { | |
Class<? extends T> implementation = getImplementation(clazz); | |
Class[] classes = new Class[parameters.length]; | |
Object[] values = new Object[parameters.length]; | |
for (int i = 0, parametersLength = parameters.length; i < parametersLength; i++) { | |
Parameter parameter = parameters[i]; | |
classes[i] = parameter.getType(); | |
values[i] = parameter.getValue(); | |
} | |
try { | |
Constructor<? extends T> constructor = implementation.getDeclaredConstructor(classes); | |
constructor.setAccessible(true); | |
return constructor.newInstance(values); | |
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) { | |
e.printStackTrace(); | |
} | |
return null; | |
} | |
@Data | |
public static class Parameter { | |
private final Class<?> type; | |
private final Object value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment