プログラマメモ2 - programmer no memo2

[java]classpath 2006/07/18
2006/11/26

Classpathクラス

実装参考は、jetty。



koders  Classpath.java





import java.io.File;

import java.io.IOException;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLClassLoader;

import java.util.Arrays;

import java.util.Vector;



public class Classpath {



Vector<File> vector = new Vector<File>();



public Classpath() {

}



public Classpath(String initial) {

addClasspath(initial);

}



public boolean addClasspath(String component) {

if ((component != null) && (component.length() > 0)) {

try {

File f = new File(component);

if (f.exists()) {

File key = f.getCanonicalFile();

if (!vector.contains(key)) {

vector.add(key);

return true;

}

}

} catch (IOException e) {

}

}

return false;

}



public boolean addClasspath(File component) {

if (component != null) {

try {

if (component.exists()) {

File key = component.getCanonicalFile();

if (!vector.contains(key)) {

vector.add(key);

return true;

}

}

} catch (IOException e) {

}

}

return false;

}



public String toString() {

StringBuffer cp = new StringBuffer();

int cnt = vector.size();

if (1 <= cnt) {

cp.append(((File) (vector.elementAt(0))).getPath());

}

for (int i = 1; i < cnt; i++) {

cp.append(File.pathSeparatorChar);

cp.append(((File) (vector.elementAt(i))).getPath());

}

return cp.toString();

}



public ClassLoader getClassLoader() {

int cnt = vector.size();

URL[] urls = new URL[cnt];

for (int i = 0; i < cnt; i++) {

try {

urls[i] = ((File) (vector.elementAt(i))).toURL();

} catch (MalformedURLException e) {

}

}



ClassLoader parent = Thread.currentThread().getContextClassLoader();

if (parent == null) {

parent = Classpath.class.getClassLoader();

}

if (parent == null) {

parent = ClassLoader.getSystemClassLoader();

}

return new MyLoader(urls, parent);

}



private class MyLoader extends URLClassLoader {

String name;



MyLoader(URL[] urls, ClassLoader parent) {

super(urls, parent);

name = "MyLoader:[" + Arrays.asList(urls) + "]";

}



public String toString() {

return name;

}

}



}





: