001/* 002 * #%L 003 * Netarchivesuite - common 004 * %% 005 * Copyright (C) 2005 - 2014 The Royal Danish Library, the Danish State and University Library, 006 * the National Library of France and the Austrian National Library. 007 * %% 008 * This program is free software: you can redistribute it and/or modify 009 * it under the terms of the GNU Lesser General Public License as 010 * published by the Free Software Foundation, either version 2.1 of the 011 * License, or (at your option) any later version. 012 * 013 * This program is distributed in the hope that it will be useful, 014 * but WITHOUT ANY WARRANTY; without even the implied warranty of 015 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 016 * GNU General Lesser Public License for more details. 017 * 018 * You should have received a copy of the GNU General Lesser Public 019 * License along with this program. If not, see 020 * <http://www.gnu.org/licenses/lgpl-2.1.html>. 021 * #L% 022 */ 023package dk.netarkivet.common.utils.batch; 024 025import java.io.File; 026 027import dk.netarkivet.common.exceptions.ArgumentNotValid; 028import dk.netarkivet.common.utils.FileUtils; 029 030/** 031 * A subclass of ClassLoader that can take a byte[] containing a class file. 032 */ 033public class ByteClassLoader extends ClassLoader { 034 035 /** Binary class data loaded from file. */ 036 private final byte[] binaryData; 037 038 /** 039 * Constructor that reads data from a file. 040 * 041 * @param binaryFile A file containing a Java class. 042 */ 043 public ByteClassLoader(File binaryFile) { 044 ArgumentNotValid.checkNotNull(binaryFile, "File binaryFile"); 045 this.binaryData = FileUtils.readBinaryFile(binaryFile); 046 } 047 048 /** 049 * Constructor taking a class as an array of bytes. 050 * 051 * @param bytes Array of bytes containing a class definition. 052 */ 053 public ByteClassLoader(byte[] bytes) { 054 ArgumentNotValid.checkNotNull(bytes, "byte[] bytes"); 055 this.binaryData = bytes; 056 } 057 058 /** 059 * Define the class that this class loader knows about. The name of the class is taken from the data given in the 060 * constructor. 061 * <p> 062 * Note that this does *not* override any of the java.lang.ClassLoader#defineClass methods. Calling this method 063 * directly is the only way to get the class defined by this classloader. 064 * 065 * @return A new Class object for this class. 066 */ 067 @SuppressWarnings("rawtypes") 068 public Class defineClass() { 069 return super.defineClass(null, binaryData, 0, binaryData.length); 070 } 071 072}