【发布时间】:2014-05-19 11:20:42
【问题描述】:
我正在尝试使用我自己的自定义类加载器调用 org.apache.commons.io.FileUtils 的方法 listFilesAndDirs()。但它返回 NoSuchMethodException。
用于方法调用的代码。
MyLoader c=new MyLoader();
Class cls=c.loadClass("org.apache.commons.io.FileUtils");
//to display the available methods
Method m[] = cls.getDeclaredMethods();
for (int i = 0; i < m.length; i++)
System.out.println(m[i].toString());
// to get a listFilesAndDirs method
Method me=cls.getMethod("listFilesAndDirs",new Class[] { File.class, IOFileFilter.class,
IOFileFilter.class });
用于类加载器的代码
public class MyLoader extends ClassLoader {
private String classPath;
public MyLoader()
{
}
private String jarFile = "D:/Project/lib/commons-io-2.4.jar";; //Path to the jar file
private Hashtable classes = new Hashtable(); //used to cache already defined classes
public Class loadClass(String className) throws ClassNotFoundException {
return findClass(className);
}
public Class findClass(String className) {
//System.out.println(className+" is loaded by Custom class Loader");
byte classByte[];
Class result = null;
result = (Class) classes.get(className); //checks in cached classes
if (result != null) {
return result;
}
try {
JarFile jar = new JarFile(jarFile);
classPath=className.replaceAll("\\.", "/");
JarEntry entry = jar.getJarEntry(classPath + ".class");
if(entry==null)
{
return findSystemClass(className);
}
else
{
InputStream is = jar.getInputStream(entry);
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
int nextValue = is.read();
while (-1 != nextValue) {
byteStream.write(nextValue);
nextValue = is.read();
}
classByte = byteStream.toByteArray();
result = defineClass(className, classByte, 0, classByte.length, null);
classes.put(className, result);
return result;
}
} catch (Exception e) {
return null;
}
}
}
调用 cls.getDeclaredMethods() 将返回方法 org.apache.commons.io.FileUtils.listFilesAndDirs(java.io.File,org.apache.commons.io.filefilter.IOFileFilter,org.apache.commons.io.filefilter.IOFileFilter)
但是 cls.getMethod("listFilesAndDirs",new Class[] { File.class, IOFileFilter.class, IOFileFilter.class }); 返回以下错误
java.lang.NoSuchMethodException: org.apache.commons.io.FileUtils.listFilesAndDirs(java.io.File, org.apache.commons.io.filefilter.IOFileFilter, org.apache.commons.io.filefilter.IOFileFilter ) 在 java.lang.Class.getDeclaredMethod(Class.java:1937) 在 Sample.main(Sample.java:30)
【问题讨论】:
标签: java class exception object classloader