Skip to content

Instantly share code, notes, and snippets.

@jackbergus
Created August 2, 2022 18:11
Show Gist options
  • Save jackbergus/4962553167bd118b81164d5ce53f8212 to your computer and use it in GitHub Desktop.
Save jackbergus/4962553167bd118b81164d5ce53f8212 to your computer and use it in GitHub Desktop.
/*
* ReflectiveFactoryMethod.java
* This file is part of ReflectiveFactoryMethod.java
*
* Copyright (C) 2022 - Giacomo Bergami
*
* ReflectiveFactoryMethod.java is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* ReflectiveFactoryMethod.java is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ReflectiveFactoryMethod.java. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.ncl.giacomobergami.utils.design_patterns;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.function.Supplier;
public class ReflectiveFactoryMethod<T> {
private ReflectiveFactoryMethod() {}
private static HashMap<String, ReflectiveFactoryMethod<?>> classMap = new HashMap<>();
public static <T> ReflectiveFactoryMethod<T> getInstance(Class<? extends T> clazz) {
if (!classMap.containsKey(clazz.getName()))
classMap.put(clazz.getName(), new ReflectiveFactoryMethod<T>());
return (ReflectiveFactoryMethod<T>)classMap.get(clazz.getName());
}
public <T> T generateFacade(String clazzPath, Supplier<T> bogus, Object... clazzez) {
if (clazzPath == null) return bogus.get();
Class<?> clazz = null;
Class<?>[] actualClazzez = new Class<?>[clazzez.length];
if (clazzPath != null) for (int i = 0; i<clazzez.length; i++) actualClazzez[i] = clazzez[i].getClass();
Constructor<? extends T> object = null;
try {
clazz = Class.forName(clazzPath);
} catch (ClassNotFoundException e) {
System.err.println("Class not found: " + clazzPath);
return bogus.get();
}
try {
object = (Constructor<? extends T>) clazz.getConstructor(actualClazzez);
} catch (NoSuchMethodException e) {
e.printStackTrace();
System.err.println("No valid constructor for: " + clazzPath);
return bogus.get();
}
try {
return object.newInstance(clazzez);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
System.err.println("No valid instantiation for: " + clazzPath);
return bogus.get();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment