Adam Paynter
Adam Paynter

Reputation: 46898

Is there a way to obtain the bytecode for a class at runtime?

In Java, is there a way (at runtime) to obtain the bytecode which defined a particular class?

Put another way, is there a way to obtain the byte[] array passed to ClassLoader.defineClass(String name, byte[] b, int off, int len) when a particular class was loaded? I see that this method is declared final, so creating a custom ClassLoader to intercept class definitions seems out of the question.

In the past, I have used the class's ClassLoader to obtain the bytecode via the getResourceAsStream(String) method, but I would prefer a more canonical solution.

Upvotes: 16

Views: 6109

Answers (2)

stacker
stacker

Reputation: 68942

Here is a description how to implement an agent

Upvotes: 10

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

"Java agents" would be the obvious solution.

Upvotes: 6

Related Questions