有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JDK:java中的命名约定。可丢弃的

Java中的所有接口,如Serializable, Cloneable, Observable等,都以“-able”作为后缀。然而,java.lang.Throwable不是一个接口,而是一个类

我理解java.lang.Throwable的用法,但我不理解它为什么以这种方式命名。这种异常现象有具体原因吗


共 (2) 个答案

  1. # 1 楼答案

    The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. Similarly, only this class or one of its subclasses can be the argument type in a catch clause.

    它包含了所有可以抛出的东西,就像接口/抽象类一样。我想这应该是使用-able后缀背后的逻辑。虽然这不是一个争论点。。。一般来说,您不应该假设任何以able结尾的东西都是一个接口

    更新
    现实生活中的另一个例子是在我的一个项目中。。。我必须创建一个(抽象的)超类,它的子类可以被缓存(在MemcacheD中)。它抽象了添加、删除、更新缓存所需的所有逻辑。什么是它的好名字?我把它命名为Cacheable。想法是如果它是Cacheable,它将被缓存

    所以,它只是语义,与命名模式无关。这里给出了Java唯一的命名模式:Java Naming Convention

  2. # 2 楼答案

    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.