Last active
February 21, 2016 20:31
-
-
Save AnnaBoro/85246487a79a1f83f660 to your computer and use it in GitHub Desktop.
+ setPrivates
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 java.util.List; | |
import java.lang.reflect.Field; | |
import java.lang.reflect.InvocationTargetException; | |
import java.lang.reflect.Method; | |
import java.util.Map; | |
public class Reflection2<T> { | |
public void setPrivates(Object o, Map<String, Object> map) throws NoSuchFieldException, IllegalAccessException { | |
for (Map.Entry<String, Object> entry : map.entrySet()) { | |
Field field = o.getClass().getDeclaredField(entry.getKey()); | |
field.setAccessible(true); | |
field.set(o, entry.getValue()); | |
field.setAccessible(false); | |
} | |
} | |
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