反射的作用
在Web框架中,反转控制(IOC)的实例化,依赖注入的赋值以及接口Handle函数的触发都是利用了反射机制,如同OC的字符串反射一样,Java里的反射也是通过类或Class进行内存的运行时(Runtime)操作.
反射的三个基本类
在Smart框架中,反射用到三个概念
- Instance: 实例class.newInstance()来新建实例
- Field: 成员变量field.set(Instance,value)来对具体实例的成员变量赋值
- Method: 成员方法,使用method.invoke(Instance,args)触发某个成员方法
Example-ReflectionUtil
package org.smart4j.framework.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectionUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionUtil.class);
public static Object newInstance(Class<?> cls) {
Object instance = null;
try {
instance = cls.newInstance();
} catch (InstantiationException e) {
LOGGER.error("new instance failure",e);
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return instance;
}
public static Object invokeMethod(Object obj, Method method, Object args) {
Object result = null;
try {
method.setAccessible(true);
result = method.invoke(obj,args);
} catch (IllegalAccessException e) {
LOGGER.error("invoke method failure",e);
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return result;
}
public static void setField(Object obj, Field field, Object value) {
try {
field.setAccessible(true);
field.set(obj, value);
} catch (IllegalAccessException e) {
LOGGER.error("set field failure",e);
throw new RuntimeException(e);
}
}
}