gpt4 book ai didi

java - 为什么是 Class.newInstance() "evil"?

转载 作者:IT老高 更新时间:2023-10-28 11:34:14 25 4
gpt4 key购买 nike

Ryan Delucchihere在评论 #3 到 Tom Hawtin的答案:

why is Class.newInstance() "evil"?

这是对代码示例的响应:

// Avoid Class.newInstance, for it is evil.
Constructor<? extends Runnable> ctor = runClass.getConstructor();
Runnable doRun = ctor.newInstance();

那么,为什么它是邪恶的?

最佳答案

Java API 文档解释了原因(http://java.sun.com/javase/6/docs/api/java/lang/Class.html#newInstance()):

Note that this method propagates any exception thrown by the nullary constructor, including a checked exception. Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler. The Constructor.newInstance method avoids this problem by wrapping any exception thrown by the constructor in a (checked) InvocationTargetException.

换句话说,它可以击败检查异常系统。

关于java - 为什么是 Class.newInstance() "evil"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/195321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com