クラスをダンプする

id:masanobuimaiさんのメモを参考にして。


public class Foo {

public static void main(String args) {
try {
Foo foo = new Foo();
foo.dump(String.class);
} catch (Exception e) {
e.printStackTrace();
}
}

public void dump(Class clazz) throws IOException {
byte bs = class2bytes(clazz);
printByteArray(bs);
}

private void printByteArray(byte bs) {
for (int i = 0; i < bs.length; i++) {
for (int j = 0; (j < 16) && (i < bs.length); j++, i++) {
int b = bs[i] & 0xff;

if (b < 0x10)
System.out.print("0");

System.out.print(Integer.toHexString(b));

if (j < 15)
System.out.print(" ");
}

System.out.println();
}
}

private byte class2bytes(Class clazz) throws IOException {
String path = clazz.getName().replace('.', '/') + ".class";
URL url = Thread.currentThread().getContextClassLoader().getResource(path);
InputStream in = url.openStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
pipe(in, out);
in.close();
return out.toByteArray();
}

private void pipe(InputStream in, OutputStream out) throws IOException {
byte[] buf = new byte[1024];
int len = 0;

while ( (len = in.read(buf) ) > 0)
out.write(buf, 0, len);
}

}