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

Easy way to generate the descriptor string to use in an ElementMatchers.hasDescriptor(String)?

Open mpet opened this issue 3 years ago • 7 comments

Hi,

I have the following code:

AnnotationDescription annotationDescription = AnnotationDescription.Latent.Builder.ofType((Class<? extends Annotation>) annotationClass).build();
		new ByteBuddy()
		  .redefine(clazz)
		  .visit(new MemberAttributeExtension.ForMethod()
		    .annotateMethod(annotationDescription)
		    .on(ElementMatchers.hasMethodName(methodName).and(ElementMatchers.hasDescriptor(descriptor))))
		  .make().load(clazz.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());

to add an annotation to a existing class and it's method.

Is there a way to create the descriptor String? We are going from javaassist to bytebuddy where we could do:

String descriptor = Descriptor.ofMethod(CtClass.intType, new CtClass[] { CtClass.intType, CtClass.intType });

//mike

mpet avatar Jun 02 '22 14:06 mpet

I'd use a matcher as:

takesArguments(int.class, int.class).and(returns(int.class))

Descriptors can be resolved via ASMs Type class.

raphw avatar Jun 02 '22 15:06 raphw

Yes I could use matchers but I have a method that should take a string as input ( that is the descriptor). Is it possible to use ASM to generate a descriptor as String? This is a requirement since methods will have different return type and parameters. So it has to be a generic input like a string that is valid for all method types.

mpet avatar Jun 03 '22 05:06 mpet

Either use Type.getDescriptor or use MethodDescription.SignatureToken.getDescriptor.

raphw avatar Jun 03 '22 07:06 raphw

So this class is the one? import aj.org.objectweb.asm.Type;

mpet avatar Jun 03 '22 09:06 mpet

Within net.bytebuddy package. That's probably another shade.

raphw avatar Jun 03 '22 09:06 raphw

image

Which one to use for Type?

mpet avatar Jun 03 '22 09:06 mpet

Found it: net.bytebuddy.jar.asm.Type.getMethodDescriptor(method) Not sure why it is in jar?

mpet avatar Jun 03 '22 09:06 mpet