Among the sevral listeners provided by TestNG, I find IAnnotationTransformer2 listener as one of the coolest ones. Th reason being, it allows to modify or change the annotations through code by changing the annotations parameters, instead of declarative approach through XML. It works at both levels viz. annotations on classes and methods. Read more about other annotation transformers here.
A simple Usecase
A scenario where the IAnnotationTransformer2 listener can be used is when you want run certain methods dynamically based on some condition. For instance, there might be a scenario when a method should be executed only when the previous test method has produced certain output(more like changed some value somewhere). In that case the enabled param for a test annotation can be set to false and that will cause the TestNG to skip the method. Same can be applied for the whole class when you want to skip the whole class.
Below is how to implement a basic version of above usecase:
Now all we have to do is tell TestNG to use this class as a listener. This can be done annotation in code or through XML. I preferred XML:
Note that if same annotations are present on class and methods, annotations at method level take precedence. So if the enabled parameter is to true on method but is false on class, the true value from the method will take precedence and the class will execute.