They seem almost redundant in the functionality they offer us. The main difference seems to be that when we redefine a class, we supply a byte[]
with the new definition out of the blue, whereas when we retransform, we get a byte[]
containing the current definition via the same API, and we return a modified byte[]
.
Therefore, to redefine, we need to know more about the class. Consider the use-case of injecting profiling trace statements. With retransform you can do that more directly: just look at the bytecode given, modify it, and return it. But if we went the redefine route, we would need to fetch the original byte[]
from somewhere (like getResourceAsStream()
).
Another apparent difference is in how we interact with other class transformers; who goes first. Transforms are applied to the original or a redefined class, so several transforms can be additive, for example.
Historically, if we look at the Since comments in the API documentation, or on page 238 of this book (Friesen 2007 Beginning Java SE 6 Platform), we notice that redefinition capabilities were introduced in Java 5, and retransformation in Java 6. My guess is that retransformation was introduced as a more general capability, but redefinition had to be retained for backwards compatibility.
Quoting the key sentence about retransformation methods from the book linked above:
Agents use these methods to retransform previously loaded classes
without needing to access their class files.
The second part of the question:
If redefinition happens before class is loaded and retransformation
after, then when does exactly retransformation happen?
No, redefinition happens after the class is loaded, as well as retransformation. They happen when you call your Instrumentation
instance's redefineClasses(..)
and retransformClasses(..)
methods, respectively.
Here is a question to any experts passing by: is there anything you can do by redefining classes, that you can't do by retransforming them? My guess is that the answer is "nothing".