PageRenderTime 24ms CodeModel.GetById 1ms app.highlight 17ms RepoModel.GetById 1ms app.codeStats 0ms

/test/kilim/test/TaskTestClassLoader.java

http://github.com/kilim/kilim
Java | 74 lines | 58 code | 8 blank | 8 comment | 10 complexity | 67bcc269055d933f2f3f4cbb27701785 MD5 | raw file
 1/* Copyright (c) 2006, Sriram Srinivasan
 2 *
 3 * You may distribute this software under the terms of the license 
 4 * specified in the file "License"
 5 */
 6
 7package kilim.test;
 8
 9import java.io.File;
10import java.io.FileInputStream;
11import java.io.IOException;
12import java.net.URL;
13
14public class TaskTestClassLoader extends ClassLoader {
15    static String wclassDir;
16
17    static {
18        URL baseURL = Thread.currentThread().getContextClassLoader().getResource("kilim/test/TaskTestClassLoader.class");
19        String path = baseURL.getPath();
20        wclassDir = path.substring(0, path.indexOf("/classes/")) + "/wclasses/";
21    }
22    
23    public TaskTestClassLoader(ClassLoader aParent) {
24        super(aParent);
25    }
26
27    @Override
28    public Class<?> loadClass(String className, boolean resolve)
29                                                           throws ClassNotFoundException {
30        Class<?> ret = findLoadedClass(className);
31        if (ret == null && className.startsWith("kilim")) {
32            File f = new File(wclassDir + className.replace('.', '/') + ".class");
33            if (f.exists()) {
34                try {
35                    byte[] bytes = getBytes(f);
36//                    if (resolve) {
37                        ret = defineClass(className, bytes, 0, bytes.length);
38//                    } 
39                } catch (IOException ioe) {
40                    System.err.println("Error loading class " + className + " from file " + f.getPath());
41                    ioe.printStackTrace();
42                    // Not supposed to happen
43                    System.exit(1);
44                }
45            }
46        }
47        if (ret == null) {
48            return resolve ? findSystemClass(className)
49                    : getParent().loadClass(className);
50        } else {
51            return ret;
52        }
53    }
54
55    private byte[] getBytes(File f) throws IOException {
56        int size = (int)f.length();
57        byte[] bytes = new byte[size];
58        int remaining = size;
59        int i = 0;
60        FileInputStream fis = new FileInputStream(f);
61        while (remaining > 0) {
62            int n = fis.read(bytes, i, remaining);
63            if (n == -1) break;
64            remaining -= n;
65            i += n;
66        }
67        return bytes;
68    }
69    
70    public static void main(String[] args) throws Exception {
71        Class<?> c = new TaskTestClassLoader(Thread.currentThread().getContextClassLoader()).loadClass(args[0], true);
72        c.newInstance();
73    }
74}