我試圖調用該方法listFilesAndDirs()。但它返回NoSuchMethodException。自定義類加載器在listFilesAndDirs返回NoSuchMethodException()使用自己的自定義類加載器org.apache.commons.io.FileUtils的方法調用
用於方法調用的代碼。用於類加載器cls.getDeclaredMethods的
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;
}
}
}
()調用將返回方法 org.apache.commons.io.FileUtils.listFilesAndDirs(java的
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 });
代碼。 io.File,org.apache.commons.io.filefilter.IOFileFilter,org.apache.commons.io.filefilter.IOFileFilter)
但cl s.getMethod( 「listFilesAndDirs」,新的等級[] {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)