ClassLoaderTarg.java revision 0:37a05a11f281
1/* 2 * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, 20 * CA 95054 USA or visit www.sun.com if you need additional information or 21 * have any questions. 22 */ 23 24/** 25 * 26 */ 27import java.util.*; 28import java.io.*; 29 30class ClassLoaderTarg extends ClassLoader { 31 private Hashtable loaded = new Hashtable(); 32 String id; 33 34 public ClassLoaderTarg(String id) { 35 this.id = id; 36 } 37 38 private byte[] loadClassBytes(String cname) 39 throws ClassNotFoundException { 40 StringTokenizer stk = new StringTokenizer(System.getProperty("java.class.path"), 41 File.pathSeparator); 42 /* search class path for the class file */ 43 while (stk.hasMoreTokens()) { 44 File cfile = new File(stk.nextToken() + File.separator + 45 cname + ".class"); 46 if (cfile.exists()) { 47 System.out.println("loading from: " + cfile); 48 return loadBytes(cfile, cname); 49 } else { 50 System.out.println("no file: " + cfile + " - trying next"); 51 } 52 } 53 throw new ClassNotFoundException(cname); 54 } 55 56 57 private byte[] loadBytes(File cfile, String cname) 58 throws ClassNotFoundException { 59 try { 60 long fsize = cfile.length(); 61 if (fsize > 0) { 62 FileInputStream in = new FileInputStream(cfile); 63 byte[] cbytes = new byte[(int)fsize]; 64 in.read(cbytes); 65 in.close(); 66 return cbytes; 67 } 68 } catch (IOException exc) { 69 // drop down 70 } 71 throw new ClassNotFoundException(cname); 72 } 73 74 public synchronized Class findClass(String cname) 75 throws ClassNotFoundException { 76 Class klass = (Class)loaded.get(cname); 77 if (klass == null) { 78 byte[] cbytes = loadClassBytes(cname); 79 klass = defineClass(cname, cbytes, 0, cbytes.length); 80 loaded.put(cname, klass); 81 System.err.println("ClassLoaderTarg (" + id +") loaded: " + cname); 82 } 83 return klass; 84 } 85 86 protected void finalize() { 87 UnloadEventTarg.classLoaderFinalized(id); 88 try { 89 super.finalize(); 90 } catch (Throwable thrown) { 91 } 92 } 93} 94