1 8 package com.tc.backport175.bytecode; 9 10 import com.tc.backport175.bytecode.spi.BytecodeProvider; 11 12 import java.io.InputStream ; 13 import java.io.IOException ; 14 15 21 public class DefaultBytecodeProvider implements BytecodeProvider { 22 23 30 public byte[] getBytecode(final String className, final ClassLoader loader) throws Exception { 31 byte[] bytes; 32 InputStream in = null; 33 try { 34 if (loader != null) { 35 in = loader.getResourceAsStream(className.replace('.', '/') + ".class"); 36 } else { 37 in = ClassLoader.getSystemClassLoader().getResourceAsStream(className.replace('.', '/') + ".class"); 38 } 39 if (in != null) { 40 bytes = toByteArray(in); 41 } else { 42 throw new Exception ("could not read class [" + className + "] as byte array"); 43 } 44 } catch (IOException e) { 45 throw new Exception ("could not read class [" + className + "]as byte array due to: " + e.toString()); 46 } finally { 47 try { 48 in.close(); 49 } catch (Exception e) { 50 ; } 52 } 53 return bytes; 54 } 55 56 63 private byte[] toByteArray(final InputStream in) throws IOException { 64 byte[] bytes = new byte[in.available()]; 65 int len = 0; 66 while (true) { 67 int n = in.read(bytes, len, bytes.length - len); 68 if (n == -1) { 69 if (len < bytes.length) { 70 byte[] c = new byte[len]; 71 System.arraycopy(bytes, 0, c, 0, len); 72 bytes = c; 73 } 74 return bytes; 75 } 76 len += n; 77 if (len == bytes.length) { 78 byte[] c = new byte[bytes.length + 1000]; 79 System.arraycopy(bytes, 0, c, 0, len); 80 bytes = c; 81 } 82 } 83 } 84 } 85 | Popular Tags |