Last active
February 21, 2016 20:28
-
-
Save AnnaBoro/36e5ddb1522a9bbfb115 to your computer and use it in GitHub Desktop.
init with constructor
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
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