嗯,难道需要编写通用的ClassLoader查询类?我写了一个...
// 摘自javax.xml.parsers.FactoryFinder
public final class ClassLoaderFinder {
private ClassLoaderFinder() {
}
/**
* Figure out which ClassLoader to use. For JDK 1.2 and later use the
* context ClassLoader if possible. Note: we defer linking the class
* that calls an API only in JDK 1.2 until runtime so that we can catch
* LinkageError so that this code will run in older non-Sun JVMs such
* as the Microsoft JVM in IE.
*/
public static ClassLoader findClassLoader() throws ConfigurationError {
ClassLoader classLoader;
try {
// Construct the name of the concrete class to instantiate
Class clazz = Class.forName(ClassLoaderFinder.class.getName()
+ "$ClassLoaderFinderConcrete");
ContextClassLoaderFinder clf = (ContextClassLoaderFinder) clazz.
newInstance();
classLoader = clf.getContextClassLoader();
}
catch (LinkageError le) {
// Assume that we are running JDK 1.1, use the current ClassLoader
classLoader = ClassLoaderFinder.class.getClassLoader();
}
catch (ClassNotFoundException x) {
// This case should not normally happen. MS IE can throw this
// instead of a LinkageError the second time Class.forName() is
// called so assume that we are running JDK 1.1 and use the
// current ClassLoader
classLoader = ClassLoaderFinder.class.getClassLoader();
}
catch (Exception x) {
// Something abnormal happened so throw an error
throw new ConfigurationError(x.toString(), x);
}
return classLoader;
}
static class ConfigurationError
extends Error {
private Exception exception;
/**
* Construct a new instance with the specified detail string and
* exception.
*/
ConfigurationError(String msg, Exception x) {
super(msg);
this.exception = x;
}
Exception getException() {
return exception;
}
}
/*
* The following nested classes allow getContextClassLoader() to be
* called only on JDK 1.2 and yet run in older JDK 1.1 JVMs
*/
private static abstract class ContextClassLoaderFinder {
abstract ClassLoader getContextClassLoader();
}
static class ClassLoaderFinderConcrete
extends ContextClassLoaderFinder {
ClassLoader getContextClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
}
//Sample
public static void main(String args[]) {
try {
final String CLASS_NAME = "oracle.jdbc.driver.OracleDriver";
Class spiClass;
ClassLoader classLoader = ClassLoaderFinder.findClassLoader();
if (classLoader == null) {
System.out.println("From Class.forName");
spiClass = Class.forName(CLASS_NAME);
}
else {
System.out.println("From ClassLoaderFinder");
spiClass = classLoader.loadClass(CLASS_NAME);
spiClass.newInstance();
}
java.sql.Connection conn = java.sql.DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:ORCL",
"scott",
"tiger");
java.sql.Statement stmt = conn.createStatement();
java.sql.ResultSet rs = stmt.executeQuery("select * from cat");
while (rs.next()) {
System.out.println(rs.getString(2));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}