java编程中,使用反射来增强灵活性(如各类框架)、某些抽象(如各类框架)及减少样板代码(如Java Bean)。
因此,反射在实际的java项目中被大量使用。
由于项目里存在反射的性能瓶颈,使用的是ReflectASM高性能反射库来优化。
因此,在空闲时间研究了下的这个库,并做了简单的Beachmark。
介绍
ReflectASM是使用字节码生成来加强反射的性能。
反射包含多种反射,这个库很简单,它提供的特性则是:
根据匹配的字符串操作成员变量。
根据匹配的字符串调用成员函数。
根据匹配的字符串调用构造函数。
这三种也恰恰是实际使用中最多的,且在特殊场景下也容易产生性能问题。
例子
举个例子,使用MethodAccess来反射调用类的函数:
Person person = new Person();
MethodAccess m = MethodAccess.get(Person.class);
Object value = m.invoke(person, "getName");
更多的例子参考官方文档,这个库本身就不大,就几个类。
实现原理
MethodAccess.get方法
static public MethodAccess get (Class type) {
ArrayList methods = new ArrayList();
boolean isInterface = type.isInterface();
if (!isInterface) {
Class nextClass = type;
while (nextClass != Object.class) {
addDeclaredMethodsToList(nextClass, methods);
nextClass = nextClass.getSuperclass();
}
} else {
recursiveAddInterfaceMethodsToList(type, methods);
}
int n = methods.size();
String[] methodNames = new String[n];
Class[][] parameterTypes = new Class[n][];
Class[] returnTypes = new Class[n];
for (int i = 0; i < n; i++) {
Method method = methods.get(i);
methodNames[i] = method.getName();
parameterTypes[i] = method.getParameterTypes();
returnTypes[i] = method.getReturnType();
}
String className = type.getName();
String accessClassName = className + "MethodAccess";
if (accessClassName.startsWith("java.")) accessClassName = "reflectasm."