byte-buddy icon indicating copy to clipboard operation
byte-buddy copied to clipboard

how to use bytebuddy to implement my code

Open yiduwangkai opened this issue 1 year ago • 2 comments

i want to implement the following code public byte[] toJsonBytes(Object o) throws Exception { return gson.toJson(o).getBytes(); }

i write the code like this Method toJsonBytesMethod = gsonClass.getDeclaredMethod("toJson", Object.class); builder = builder.method(ElementMatchers.named("toJsonBytes")) .intercept(MethodCall.invoke(toJsonBytesMethod).onField("gson") .withArgument(0) .andThen(MethodCall.invoke(String.class.getDeclaredMethod("getBytes")) .with("UTF-8")) );

but when i run that, It has the following exception Exception in thread "main" java.lang.IllegalStateException: public byte[] java.lang.String.getBytes() does not accept 1 arguments at net.bytebuddy.implementation.MethodCall$Appender.toStackManipulation(MethodCall.java:3553) at net.bytebuddy.implementation.MethodCall$Appender.apply(MethodCall.java:3522) at net.bytebuddy.implementation.bytecode.ByteCodeAppender$Compound.apply(ByteCodeAppender.java:156) at net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod$WithBody.applyCode(TypeWriter.java:730) at net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod$WithBody.applyBody(TypeWriter.java:715) at net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod.apply(TypeWriter.java:622) at net.bytebuddy.dynamic.scaffold.TypeWriter$Default$ForCreation.create(TypeWriter.java:6043) at net.bytebuddy.dynamic.scaffold.TypeWriter$Default.make(TypeWriter.java:2224) at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$UsingTypeWriter.make(DynamicType.java:4050) at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:3734) at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$Delegator.make(DynamicType.java:3986) at com.bytebuddy.test.json.gson.GsonBuddyTest.getGsonStrategy(GsonBuddyTest.java:116) at com.bytebuddy.test.json.gson.GsonBuddyTest.main(GsonBuddyTest.java:21)

how i can solve that, pls help me, thx

yiduwangkai avatar Jul 13 '23 15:07 yiduwangkai

You should probably try String.class.getDeclaredMethod("getBytes", String.class)

dogourd avatar Jul 14 '23 06:07 dogourd

class i have solve that, builder = builder.method(ElementMatchers.named("toJsonBytes")) .intercept(MethodCall.invoke(String.class.getDeclaredMethod("getBytes")). onMethodCall(MethodCall.invoke(toJsonBytesMethod).onField("gson").withArgument(0)));

yiduwangkai avatar Jul 14 '23 11:07 yiduwangkai