---
title: "获取class类字节数组的方法"
author: "pcpig"
date: "2013-09-26T18:04:56Z"
tags: []
categories: ["编程语言"]
slug: "class"
draft: false
lastmod: "2013-09-26T18:56:48Z"
id: 1947866
url: "https://pcpig.iteye.com/blog/1947866"
---

研究jvm hotswap的过程中，有一步需要读取java class的字节流，本来想只提供一个class就好了，但是在Web项目下不通用，先记录下来，留待以后使用。


```java
	private static byte[] loadBytes(Class<?> cls) throws IOException {
		if (cls == null)
			return null;

		String name = cls.getCanonicalName().replaceAll("\\.", "/") + ".class";

		InputStream is = ClassLoader.getSystemResourceAsStream(name);

		BufferedInputStream bis = new BufferedInputStream(is);
		try {
			int length = is.available();
			byte[] bs = new byte[length];
			System.err.println("ddd:" + bs.length);
			bis.read(bs);

			// is.close();
			return bs;
		} finally {
			bis.close();
		}
	}
```


ps:
-javaagent:$CATALINA_BASE/lib/classreloader-1.0.0.jar