从ClassLoader获取类文件
/* * Copyright 2014 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //package com.nowjava; import java.io.Closeable; /** from n o w j a v a . c o m - 时 代 Java**/ import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; public class Main { public static byte[] getClassFile(ClassLoader classLoader, String className) { if (classLoader == null) { classLoader = ClassLoader.getSystemClassLoader(); } if (className == null) { throw new NullPointerException("className must not be null"); }/*from 时 代 J a v a - N o w J a v a . c o m*/ final InputStream is = classLoader.getResourceAsStream(className .replace('.', '/') + ".class"); if (is == null) { throw new RuntimeException("No such class file: " + className); } ReadableByteChannel channel = Channels.newChannel(is); ByteBuffer buffer; try { buffer = ByteBuffer.allocate(is.available()); while (channel.read(buffer) >= 0) { if (buffer.remaining() == 0) { buffer.flip(); ByteBuffer newBuffer = ByteBuffer.allocate(buffer .capacity() * 2); newBuffer.put(buffer); buffer = newBuffer; } } } catch (IOException e) { throw new RuntimeException(e); }