16

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.

stacker
  • 68,052
  • 28
  • 140
  • 210
Adam Paynter
  • 46,244
  • 33
  • 149
  • 164
  • Why is getResourceAsStream(String) not canonical ? – Riduidel Apr 29 '10 at 12:39
  • 2
    @Riduidel: Not all class loaders expose the bytecode as a resource. For example, some custom class loaders generate bytecode *on the fly* and don't bother returning it when `getResourceAsStream` is called. – Adam Paynter Apr 29 '10 at 12:41
  • This might be a silly question, but why do you need to get the byte codes for a given class? Presumably you don't want to use getResourceAsStream because some classes might be loaded by another classloader? – Geoff Apr 29 '10 at 13:29
  • @Geoff: I actually want the debugging symbols to help infer method parameter names at runtime as per this question: http://stackoverflow.com/questions/2729580 – Adam Paynter Apr 29 '10 at 13:57
  • @Geoff: In the past, I used the *class's* class loader (as opposed to the current thread's class loader or the system class loader) to increase the odds of finding the bytecode. :) – Adam Paynter Apr 29 '10 at 14:00

2 Answers2

9

Here is a description how to implement an agent

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
stacker
  • 68,052
  • 28
  • 140
  • 210
5

"Java agents" would be the obvious solution.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305