74 lines
2.4 KiB
Java
74 lines
2.4 KiB
Java
package com.mogo.utils;
|
|
|
|
import android.util.Log;
|
|
|
|
import java.lang.reflect.Constructor;
|
|
import java.lang.reflect.Field;
|
|
import java.lang.reflect.Method;
|
|
|
|
|
|
@SuppressWarnings("rawtypes")
|
|
public class ReflectUtils {
|
|
|
|
public static Object getField( Class clazz, Object target, String name) throws Exception {
|
|
Field field = clazz.getDeclaredField(name);
|
|
field.setAccessible(true);
|
|
return field.get(target);
|
|
}
|
|
|
|
public static void setField( Class clazz, Object target, String name, Object value) throws Exception {
|
|
Field field = clazz.getDeclaredField(name);
|
|
field.setAccessible(true);
|
|
field.set(target, value);
|
|
}
|
|
|
|
public static void setFieldNoException( Class clazz, Object target, String name, Object value) {
|
|
try {
|
|
ReflectUtils.setField(clazz, target, name, value);
|
|
} catch ( Exception e) {
|
|
Log.e("ReflectUtil",e.getMessage(),e);
|
|
}
|
|
}
|
|
|
|
@SuppressWarnings("unchecked")
|
|
public static Object invoke( Class clazz, Object target, String name, Object... args)
|
|
throws Exception {
|
|
Class[] parameterTypes = null;
|
|
if (args != null) {
|
|
parameterTypes = new Class[args.length];
|
|
for (int i = 0; i < args.length; i++) {
|
|
parameterTypes[i] = args[i].getClass();
|
|
}
|
|
}
|
|
|
|
Method method = clazz.getDeclaredMethod(name, parameterTypes);
|
|
method.setAccessible(true);
|
|
return method.invoke(target, args);
|
|
}
|
|
|
|
@SuppressWarnings("unchecked")
|
|
public static Object invoke( Class clazz, Object target, String name, Class[] parameterTypes, Object... args)
|
|
throws Exception {
|
|
Method method = clazz.getDeclaredMethod(name, parameterTypes);
|
|
method.setAccessible(true);
|
|
return method.invoke(target, args);
|
|
}
|
|
|
|
@SuppressWarnings("unchecked")
|
|
public static <T> T invokeConstructor( Class<T> clazz, Class[] parameterTypes, Object... args)
|
|
throws Exception {
|
|
Constructor constructor = clazz.getDeclaredConstructor(parameterTypes);
|
|
constructor.setAccessible(true);
|
|
return (T) constructor.newInstance(args);
|
|
}
|
|
|
|
@SuppressWarnings("unchecked")
|
|
public static <T> T invokeConstructor( Class<T> clazz)
|
|
throws Exception {
|
|
Constructor constructor = clazz.getDeclaredConstructor();
|
|
constructor.setAccessible(true);
|
|
return (T) constructor.newInstance();
|
|
}
|
|
|
|
}
|