以下是我使用的代码:
public class loader extends URLClassLoader {
public static void main(String[] args)throws Exception{
Object localObject =
new loader(loader.class.getClassLoader(),
new File(loader.class.getProtectionDomain().getCodeSource()
.getLocation().getPath())
);
(...)
}
private loader(ClassLoader paramClassLoader, File paramFile){
super(new URL[] { paramFile.toURI().toURL() }, paramClassLoader);
if (paramClassLoader == null)
throw new IllegalArgumentException("Error loading class");
}
}
错误:
loader.java:123: error: unreported exception MalformedURLException; must be caught or declared to be thrown
super(new URL[] { paramFile.toURI().toURL() }, paramClassLoader);
该如何解决呢?
发布于 2018-08-23 10:10:36
用以下代码来解决:
private static URL convertFileToURL(File file) {
try {
return file.toURI().toURL();
} catch (MalformedURLException e) {
throw new RuntimeException("Unable to convert file to URL", e);
}
}
然后:
private loader(ClassLoader paramClassLoader, File paramFile){
super(new URL[] { convertFileToURL(paramFile) }, paramClassLoader);
if (paramClassLoader == null)
throw new IllegalArgumentException("Error loading class");
}
发布于 2018-08-23 11:22:20
只需将MalformedURLException抛出到加载器构造函数中,并在Main方法中使用TRY CATCH块包装代码即可
public class loader extends URLClassLoader {
public static void main(String[] args) throws Exception {
try {
Object localObject = new loader(loader.class.getClassLoader(),
new File(loader.class.getProtectionDomain().getCodeSource()
.getLocation().getPath()));
} catch (MalformedURLException e) {
// ..
}
}
private loader(ClassLoader paramClassLoader, File paramFile)
throws MalformedURLException {
super(new URL[] { paramFile.toURI().toURL() }, paramClassLoader);
if (paramClassLoader == null) {
throw new IllegalArgumentException("Error loading class");
}
}
}
https://stackoverflow.com/questions/-100002369
复制相似问题