我尝试编写自己的loader-class来加载一个加密类。
因此,我还会覆盖调用loader(ClassLoader paramClassLoader, File paramFile)
的构造super(new URL[] { paramFile.toURI().toURL() }, paramClassLoader);
。
调用“.toUrl()”可以抛出MalformedURLException
,因此编译以下代码......
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);
如何捕获此异常? try-catch-block是不可能的,因为“对super的调用必须是构造函数中的第一个语句”。
答案 0 :(得分:7)
超类构造函数实际上没有抛出异常;它被URI.toURL()
引发(或者至少被声称可能被抛出),你在参数中调用了超类构造函数。
一种选择是编写一个静态方法将该异常转换为未经检查的异常:
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");
}
这假设您认为这是基本上不可能发生的事情,或者至少您不希望呼叫者关心的事情。我不太了解URI.toURL
是否实际关注基于文件的URI。
如果调用者应该关心,因为它可能发生在现实生活中并且他们应该处理它(我认为这不可能是诚实的)你应该声明你的构造函数可以抛出异常。
顺便说一句,请将您的类重命名为符合Java命名约定的更有意义的内容。
答案 1 :(得分:3)
只需将MalformedURLException抛出到loader构造函数并使用try catch块在main方法中包装代码。
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");
}
}
}