Created
April 18, 2023 15:24
-
-
Save yabetancourt/02ce7a41cdb11077065c4c47cb491806 to your computer and use it in GitHub Desktop.
Haciendo una factory generica para un constructor no vacio
This file contains 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
package cu.uclv.postgrade.ui.view.entity; | |
import cu.uclv.postgrade.data.entity.professor.CourseProfessor; | |
import cu.uclv.postgrade.data.entity.professor.TrainingProfessor; | |
public record EditionProfessorFactory<T>(Class<T> entityClass) implements HasEntityComplexConstructor<T> { | |
public static EditionProfessorFactory<CourseProfessor> courseProfessor = new EditionProfessorFactory<>(CourseProfessor.class); | |
public static EditionProfessorFactory<TrainingProfessor> trainingProfessor = new EditionProfessorFactory<>(TrainingProfessor.class); | |
} |
This file contains 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
package cu.uclv.postgrade.ui.view.entity; | |
import java.lang.reflect.Constructor; | |
import java.lang.reflect.InvocationTargetException; | |
import java.util.Arrays; | |
public interface HasEntityComplexConstructor<T> { | |
Class<T> entityClass(); | |
default T getEntityInstance(Object... args) { | |
T instance; | |
try { | |
Class<?>[] parameterTypes = Arrays.stream(args) | |
.map(Object::getClass) | |
.toArray(Class[]::new); | |
Constructor<T> constructor = entityClass().getConstructor(parameterTypes); | |
instance = constructor.newInstance(args); | |
} catch (InstantiationException | InvocationTargetException | IllegalAccessException | | |
NoSuchMethodException e) { | |
throw new RuntimeException(e); | |
} | |
return instance; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment