public static Class createProxy(final Class<?> classToProxy, final ClassLoader cl, final Class... interfaces) {
return createProxy(classToProxy, cl, classToProxy.getName() + "$$LocalBeanProxy", interfaces);
}
public static byte[] generateProxy(final Class<?> classToProxy, final String proxyName, final Class<?>... interfaces) throws ProxyGenerationException {
final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
final String proxyClassFileName = proxyName.replace('.', '/');
final String classFileName = classToProxy.getName().replace('.', '/');
// push class signature
final String[] interfaceNames = new String[interfaces.length];
for (int i = 0; i < interfaces.length; i++) {
final Class<?> anInterface = interfaces[i];
interfaceNames[i] = anInterface.getName().replace('.', '/');
}
cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, proxyClassFileName, null, classFileName, interfaceNames);
cw.visitSource(classFileName + ".java", null);
cw.visitAnnotation("L" + Proxy.class.getName().replace('.', '/') + ";", true).visitEnd();
// push InvocationHandler fields
cw.visitField(ACC_FINAL + ACC_PRIVATE, BUSSINESS_HANDLER_NAME, "Ljava/lang/reflect/InvocationHandler;", null, null).visitEnd();
cw.visitField(ACC_FINAL + ACC_PRIVATE, NON_BUSINESS_HANDLER_NAME, "Ljava/lang/reflect/InvocationHandler;", null, null).visitEnd();
final Map<String, List<Method>> methodMap = new HashMap<String, List<Method>>();
getNonPrivateMethods(classToProxy, methodMap);
for (final Class<?> anInterface : interfaces) {
getNonPrivateMethods(anInterface, methodMap);
}
// Iterate over the public methods
for (final Map.Entry<String, List<Method>> entry : methodMap.entrySet()) {
for (final Method method : entry.getValue()) {
final String name = method.getName();
if (Modifier.isPublic(method.getModifiers())
|| method.getParameterTypes().length == 0 && ("finalize".equals(name)
|| "clone".equals(name))) {
// forward invocations of any public methods or
// finalize/clone methods to businessHandler
processMethod(cw, method, proxyClassFileName, BUSSINESS_HANDLER_NAME);
} else {
// forward invocations of any other methods to nonBusinessHandler
processMethod(cw, method, proxyClassFileName, NON_BUSINESS_HANDLER_NAME);
}
}
}
return cw.toByteArray();
}