如何在Groovy/Java中动态生成接口/抽象类实例?
可实现动态生成接口/抽象类实例的Java/Groovy技术方案
Java原生动态代理
Java自带的方案,无需额外依赖,仅支持代理接口。通过java.lang.reflect.Proxy类和InvocationHandler接口,在invoke方法中获取目标方法的注解信息,以此定制方法行为:Foo foo = (Foo) Proxy.newProxyInstance( Foo.class.getClassLoader(), new Class[]{Foo.class}, (proxy, method, args) -> { SomeAnnotation anno = method.getAnnotation(SomeAnnotation.class); // 根据注解编写自定义逻辑 return null; } );CGLIB
字节码生成库,支持代理抽象类和接口(通过生成子类/实现类的方式)。借助MethodInterceptor拦截方法调用,处理注解相关逻辑:Enhancer enhancer = new Enhancer(); enhancer.setInterfaces(new Class[]{Foo.class}); // 处理抽象类时改用setSuperclass enhancer.setCallback((MethodInterceptor) (obj, method, args, proxy) -> { SomeAnnotation anno = method.getAnnotation(SomeAnnotation.class); // 基于注解定制方法行为 return proxy.invokeSuper(obj, args); // 或直接返回自定义结果 }); Foo foo = (Foo) enhancer.create();Groovy原生特性
利用Groovy自带的动态能力,无需额外依赖即可快速实现需求。用as关键字配合闭包生成接口实例,闭包内通过反射获取方法注解并处理:def foo = [foo: { -> def method = Foo.getMethod("foo") def anno = method.getAnnotation(SomeAnnotation) // 编写注解对应的业务逻辑 }] as Foo针对抽象类,还可以用
GroovyClassLoader动态生成子类实例,灵活性更强。Byte Buddy
简洁易用的字节码操作库,支持代理接口、抽象类甚至普通类。可直接通过注解匹配目标方法,绑定对应的处理逻辑:Foo foo = new ByteBuddy() .implement(Foo.class) // 处理抽象类时改用subclass .method(ElementMatchers.isAnnotatedWith(SomeAnnotation.class)) .intercept(MethodDelegation.to(new Object() { @RuntimeType public Object handle(@Origin Method method) { SomeAnnotation anno = method.getAnnotation(SomeAnnotation.class); // 注解对应的自定义处理逻辑 return null; } })) .make() .load(Foo.class.getClassLoader()) .getLoaded() .newInstance();
内容的提问来源于stack exchange,提问作者Adrian Shum
相关产品推荐
相关产品推荐

