Тест скорости:
package test;
import net.sf.cglib.reflect.FastClass;
import net.sf.cglib.reflect.FastMethod;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
public class Test {
private static final long SLEEP = 0;
private static final Object[] withoutParameters = new Object[0];
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InterruptedException, IllegalAccessException {
final Method[] methods = getMethods(Test.class, "command1", "command2");
final FastMethod[] fastMethods = getFastMethods(Test.class, methods);
final Test test = new Test();
final int loop = 10* 1000 * 1000;
long timeStamp = System.currentTimeMillis();
for (int i = 0; i < loop; i++) {
test.functionDirectCall();
}
System.out.println("DirectCall time:" + (System.currentTimeMillis() - timeStamp));
timeStamp = System.currentTimeMillis();
for (int i = 0; i < loop; i++) {
test.functionMethod(methods);
}
System.out.println("Method time:" + (System.currentTimeMillis() - timeStamp));
timeStamp = System.currentTimeMillis();
for (int i = 0; i < loop; i++) {
test.functionFastMethod(fastMethods);
}
System.out.println("FastMethod time:" + (System.currentTimeMillis() - timeStamp));
}
private void functionDirectCall() throws InterruptedException {
this.command1();
Thread.sleep(SLEEP);
this.command2();
Thread.sleep(SLEEP);
}
private void functionMethod(Method... methods) throws InvocationTargetException, IllegalAccessException, InterruptedException {
for (Method method : methods) {
method.invoke(this);
Thread.sleep(SLEEP);
}
}
private void functionFastMethod(FastMethod... fastMethods) throws InvocationTargetException, InterruptedException {
for (FastMethod fastMethod : fastMethods) {
fastMethod.invoke(this, withoutParameters);
Thread.sleep(SLEEP);
}
}
private static Method[] getMethods(final Class aClass, final String... methodNames) throws NoSuchMethodException {
return new ArrayList<Method>() {{
for (String methodName : methodNames) {
final Method method = aClass.getDeclaredMethod(methodName);
method.setAccessible(true);
this.add(method);
}
}}.toArray(new Method[methodNames.length]);
}
private static FastMethod[] getFastMethods(final Class aClass, final Method... methods) {
final FastClass fastClass = FastClass.create(aClass);
return new ArrayList<FastMethod>() {{
for (Method method : methods) {
add(fastClass.getMethod(method));
}
}}.toArray(new FastMethod[methods.length]);
}
public void command1() throws InterruptedException {
Thread.sleep(SLEEP);
}
public void command2() throws InterruptedException {
Thread.sleep(SLEEP);
}
}
Выход:
DirectCall time:17615
Method time:19051
FastMethod time:17952