给定class A
公共方法overrideMe(B that, C arg)
,第二个class B
使用私有方法callMe(C arg)
。是否可以使用bytebuddy生成一个子类,该子类将从已实现的callMe(C arg)
调用私有方法overrideMe(B that, C arg)
?这基本上会模仿JVM反射GeneratedMethodAccessor,它正是这样做的。
目前,我正在尝试使用这样的MethodCall:
Method callMeHandler = B.class.getDeclaredMethod("callMe");
callMeHandler.setAccessible(true);
MethodCall methodCall = MethodCall.invoke(callMeHandler).onArgument(0);
if(callMeHandler.getParameterCount() == 1)
methodCall = methodCall.withArgument(1);
Composable coercedMethodCall = methodCall
.withAssigner(ReferenceTypeAwareAssigner.INSTANCE, Typing.DYNAMIC);
String className = callMeHandler.getDeclaringClass().getName()
+ "$_generatedAccessor$" + callMeHandler.getName()
+ "$" + accessorCounter.getAndIncrement();
new ByteBuddy().subclass(GeneratableHandlerInvocation.class)
.name(className)
.method(ElementMatchers.named("invoke"))
.intercept(Advice.to(GeneratableHandlerInvocation.class)
.wrap(coercedMethodCall))
.make()
.load(callMeHandler.getDeclaringClass().getClassLoader())
.getLoaded()
.newInstance();
,但它抱怨
java.lang.IllegalStateException: Cannot invoke private void com.mycompany.secret.B.callMe() virtually
at net.bytebuddy.implementation.MethodCall$MethodInvoker$ForVirtualInvocation$WithImplicitType.invoke(MethodCall.java:2124)
at net.bytebuddy.implementation.MethodCall$Appender.apply(MethodCall.java:2400)
at net.bytebuddy.asm.Advice$Appender$EmulatingMethodVisitor.resolve(Advice.java:7156)
at net.bytebuddy.asm.Advice$Appender.apply(Advice.java:7109)
at net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod$WithBody.applyCode(TypeWriter.java:614)
at net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod$WithBody.applyBody(TypeWriter.java:603)
at net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod.apply(TypeWriter.java:521)
at net.bytebuddy.dynamic.scaffold.TypeWriter$Default$ForCreation.create(TypeWriter.java:4102)
at net.bytebuddy.dynamic.scaffold.TypeWriter$Default.make(TypeWriter.java:1612)
at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:174)
at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:155)
at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:2560)
at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$Delegator.make(DynamicType.java:2662)
at com.mycompany.secret.Main.defineTheSpecialClass(Main.java:190)
答案 0 :(得分:0)
不,这是不可能的。 JVM的字节码验证器禁止它。因此,Byte Buddy不允许您首先创建这样的方法调用。
如果您想更改类并允许这样的调用,请查看Byte Buddy的代理API和允许您更改现有代码的mail($email_to, $email_subject, $email_message, $headers);
类。