Skip to content

Instantly share code, notes, and snippets.

@AnnaBoro
Last active February 21, 2016 20:28
Show Gist options
  • Save AnnaBoro/36e5ddb1522a9bbfb115 to your computer and use it in GitHub Desktop.
Save AnnaBoro/36e5ddb1522a9bbfb115 to your computer and use it in GitHub Desktop.
init with constructor
package lesson7_10.reflection;
import com.sun.tools.javac.util.List;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
public class Reflection2<T> {
public T initClass(Class<T> tClass, List<Object> objectList) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class[] classes = new Class[objectList.size()];
for (int i = 0; i < objectList.size(); i++){
classes[i] = objectList.get(i).getClass();
}
T oClass = tClass.getConstructor(classes).newInstance(objectList.toArray());
return oClass;
}
public T initClass(Class<T> tClass, Map<String, Object> map) throws IllegalAccessException, InstantiationException, InvocationTargetException {
T oClass = tClass.newInstance();
Method[] methods = oClass.getClass().getDeclaredMethods();
for (Map.Entry<String, Object> entry : map.entrySet()) {
for (Method method : methods) {
if (method.getName().equalsIgnoreCase("set" + entry.getKey())) {
method.invoke(oClass, entry.getValue());
}
}
}
return oClass;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment