Java 中的所有接口(如Serializable, Cloneable, Observable
etc)都以“-able”为后缀。但是,java.lang.Throwable
不是接口而是类。
我理解的用法,java.lang.Throwable
但我不明白为什么它以这种方式命名。这种异常是否有特定原因?
Java 中的所有接口(如Serializable, Cloneable, Observable
etc)都以“-able”为后缀。但是,java.lang.Throwable
不是接口而是类。
我理解的用法,java.lang.Throwable
但我不明白为什么它以这种方式命名。这种异常是否有特定原因?
Sun 的前副总裁兼 Java 的主要架构师 James Gosling对互联网垃圾箱的采访解释了为什么决定让 Throwable 成为一个类而不是一个接口。主要原因是因为 throwables 需要跟踪状态:
JDC: Why is Throwable not an interface? The name kind of suggests it should have been.
Being able to catch for types, that is, something like try{}catch (<some interface or
class>), instead of only classes. That would make [the] Java [programming language]
much more flexible.
JG: The reason that the Throwable and the rest of those guys are not interfaces is
because we decided, or I decided fairly early on. I decided that I wanted to have some
state associated with every exception that gets thrown. And you can't do that with
interfaces; you can only do that with classes. The state that's there is basically
standard. There's a message, there's a snapshot, stuff like that — that's always there.
and also, if you make Throwable an interface the temptation is to assign, to make any
old object be a Throwable thing. It feels stylistically that throwing general objects
is probably a bad idea, that the things you want to throw really ought to be things
that are intended to be exceptions that really capture the nature of the exception and
what went on. They're not just general data structures.
Throwable 类是 Java 语言中所有错误和异常的超类。只有作为此类(或其子类之一)的实例的对象才会被 Java 虚拟机抛出或者可以被 Java throw 语句抛出。同样,只有此类或其子类之一可以是 catch 子句中的参数类型。
它包含所有可以抛出的东西,就像接口/抽象类所做的那样。我想这应该是有-able
后缀背后的逻辑。虽然这不是一个争论点……但一般来说,您不应该假设任何able
以接口结尾的东西。
更新
现实生活中的另一个例子是在我的一个项目中......我必须制作一个(抽象的)超类,它的子类可以被缓存(在 MemcacheD 中)。它抽象了添加、删除、更新缓存所需的所有逻辑。给它取个好听的名字是什么?我命名它Cacheable
。这个想法是,如果它是Cacheable
,它将被缓存。
所以,这只是语义——与命名模式无关。这里给出了 Java 唯一的命名模式:Java Naming Convention