为什么java.lang.Throwable不是抽象类? [英] why isn't java.lang.Throwable an abstract class?

查看:205
本文介绍了为什么java.lang.Throwable不是抽象类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:为什么-is-java-lang-throwable-a-class

嗨!我不明白为什么Throwable不是抽象类。我只看到一种用例:在记录系统中找出呼叫层次。但这可以是此类或其他类的一些静态方法。那么,为什么?)

Hi! I doesn't understand why Throwable isn't abstract class. I see only one use case for these: in logging systems for figure out call hierarchy. But it can be some static method for this or other class. So, why?)

谢谢。

upd

from java.util.logging.LogRecord

from java.util.logging.LogRecord

// Get the stack trace.
StackTraceElement stack[] = (new Throwable()).getStackTrace();

为什么不能 Throwable.getStackTrace(); 或java.lang.Thread

Why it can't be Throwable.getStackTrace(); or as in java.lang.Thread

(new Exception()).getStackTrace();

通过这种方式,我们可以避免抛出新的Throwable();

In this way we can avoid throw new Throwable();

upd2 来自Javadoc的

upd2 from javadoc


Throwable类是
Java语言中所有错误和异常的超类

The Throwable class is the superclass of all errors and exceptions in the Java language.



<所以,作为超类,它应该是抽象的,恕我直言。通过此定义,使用它来获取stacktrace并不是一个好例子。

So, as a superclass it should be abstract, imho. Using it for getting stacktrace isn't good case by this definition.

推荐答案


我不理解为什么Throwable
不是抽象类。

I doesn't understand why Throwable isn't abstract class.

答案明确指出

The answer is clearly stated here.


为什么不能将
投掷。 getStackTrace();或像
java.lang.Thread

Why it can't be Throwable.getStackTrace(); or as in java.lang.Thread

一样, getStackTrace()调用 getOurStackTrace()方法,该方法是非静态的。如果 getStackTrace()是静态的,则 getOurStackTrace()也应该是静态的。由于 printStackTrace()方法使用 getOurStackTrace(),因此不会发生这种情况。在JavaDoc中对此进行了详细说明:

Quite simply, the getStackTrace() calls the getOurStackTrace() method which is non-static. If getStackTrace() was static, so should getOurStackTrace(). This won't happen as printStackTrace() method uses the getOurStackTrace(). This is elaborated in the JavaDoc:


提供对
printStackTrace()打印的
堆栈跟踪信息的编程访问。

Provides programmatic access to the stack trace information printed by printStackTrace().

java.lang.Throwable的源代码:

Source for java.lang.Throwable:

 public StackTraceElement[] getStackTrace() {
        return (StackTraceElement[]) getOurStackTrace().clone();
    }


另外,如果您阅读了 getOurStackTrace()方法,您会看到它调用以下方法:

Also, if you read the code of getOurStackTrace() method, you'll see it calls the following method:

private native int getStackTraceDepth();

据我所知, native 不能是静态的(我可能是错误的)。

这篇关于为什么java.lang.Throwable不是抽象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆