feature request: byte-buddy-proxy lightweight jar
Byte-Buddy is a very powerful, customizable lib, which makes it extremely versatile. With this great power however comes significant weight. Usually around 3.7MB in my case (after minimizing with maven-shade-plugin) to be specific ;-] In case of environments with limited resources (smart cards, embedded systems, IoT devices) this may be a significant problem. OTOH many projects that use byte-buddy really require very small fraction of its functionality. Therefore it would be super mega cool if apart from the main almighty byte-buddy.jar there were also other smaller jars that provide commonly used subsets of its functionality.
One particular example, that I'm dreaming of often is a lightweight jar that only allows to create proxies for classes using a supplied InvocationHandler. In several of my projects my only use of byte-buddy was something like this:
<T> Class<? extends T> createProxyClass(Class<? extends T> aClass) {
DynamicType.Builder<? extends T> proxyClassBuilder = new ByteBuddy()
.subclass(aClass)
.name(getClass().getPackageName() + ".ProxyFor_" + aClass.getName().replace('.', '_'))
.defineField(
PROXY_DECORATOR_FIELD_NAME,
InvocationHandler.class,
Visibility.PACKAGE_PRIVATE)
.method(ElementMatchers.any())
.intercept(InvocationHandlerAdapter.toField(PROXY_DECORATOR_FIELD_NAME));
for (var annotation: aClass.getAnnotations()) {
proxyClassBuilder = proxyClassBuilder.annotateType(annotation);
}
try (
final var unloadedClass = proxyClassBuilder.make();
) {
return unloadedClass
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
.getLoaded();
}
}
...and each time it introduces 3.7MB which limits applicability in the previously mentioned situations :(
My dream is to have a jar whose only functionality is something like this:
T myProxy = ByteBuddyProxyBuilder.newProxy(targetClassLoader, classToProxify, proxyInvocationHandler);
...and weights below 1MB ;-)
(ideally ByteBuddyProxyBuilder should maintain a cache of created dynamic proxies per ClassLoader, so if I ask for a proxy for the same class in the same classLoader, the previously created dynamic class will be reused. It should also copy all annotations from classToProxify. Optionally there could be a second version of newProxy that has an additional Annotation[] annotationsForProxyClass param).
I honestly have no idea how feasible this idea is and how much work it requires: it's just a dream of an average user who knows virtually nothing about the byte-code stuff ;-)
This would be hard to create. I tested the idea by deleting all code that would not be needed to run the above example and it's still most code as Byte Buddy abstracts over the type system.
However, in cases like yours I would recommend to move the proxy generation to build time. At runtime, you would then only instantiate the proxy. If memory is sparse, that gives you the least overhead available.
Byte Buddy offers a build plugin for that, too.