方法签名声明为 throws Exception;实现为抛出 Exception 的子类
我有以下接口声明:
public interface SomeInterface {
void someMethod() throws Exception;
}
我使用第三方生成此类的实现(JavaCC - 出于好奇)
生成的类天真地看起来像这样:
public class SomeClass implements SomeInterface {
public void someMethod() throws SomeException {
// Does something
}
}
其中 SomeException
当然是 < 的子类代码>异常。
(并不)令人惊讶的是代码无法编译。
有人对此有任何意见吗?
谢谢!
编辑:
将方法SomeMethod()
重命名为someMethod()
。
这是我的一个拼写错误...(抱歉)
编辑 #2:
抱歉 - 我犯了一个巨大的错误。编写这个示例迫使我精简代码。我没有注意到错误是在其他地方而不是签名。
这就是运行时编译和自定义类加载的“魔力”......
I have the following interface declaration:
public interface SomeInterface {
void someMethod() throws Exception;
}
I use a third party to generate an implementation of this class (JavaCC - for the curious)
The generated class looks naively like this:
public class SomeClass implements SomeInterface {
public void someMethod() throws SomeException {
// Does something
}
}
Where SomeException
is of course a subclass of Exception
.
(Not) surprisingly the code does not compile.
Does anyone have any input concerning this?
Thanks!
EDIT:
renamed the method SomeMethod()
to someMethod()
.
It had been a typo of mine... (sorry)
EDIT #2:
Sorry all - huge mistake of mine. Writing this example had forced me to strip down the code. I had not noticed that the mistake was elsewhere and not with the signature.
Thats the "magic" of runtime compile and custom class loading...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它无法编译,因为方法名称不相同(检查 S/someMethod 上的大写字母)
It doesn't compile because the method names aren't the same (check the caps on S/someMethod)
Java 中大小写很重要。你的接口说
someMethod
,你的类说SomeMethod
。Case is important in Java. Your interface says
someMethod
and your class saysSomeMethod
.为什么你的接口方法会抛出异常?这几乎总是错误的。例外只是其余扩展的基本类型;它不应该这样使用。
Why does your interface method throw Exception? This is almost always wrong. Exception is just the base type the rest extend from; it's not meant to be used this way.
其中一种方法保护是公共的,另一种是默认的,这就是您的代码无法编译的原因。将两者设为公开或默认。
One of the methods protection is public and the other is default, that's why your code does not compile. Make both public or default.