如何使用反射检查方法

发布于 2024-12-06 04:38:45 字数 237 浏览 0 评论 0原文

public void foo(){
    throw new Exception("foo");
}


public void bar(){
    foo();
}

是否可以检查方法 bar() 以便知道在 bar 内没有 try catch 的情况下调用了 foo() ()?

public void foo(){
    throw new Exception("foo");
}


public void bar(){
    foo();
}

Is it possible to inspect the method bar() in order to know that foo() is called without a try catch inside bar()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

_蜘蛛 2024-12-13 04:38:45

您可能有兴趣将整个类包装在代理中,并使用 InvocableHandler 来观察它:

http: //www.javalobby.org/java/forums/t18631.html

我猜,如果您的 IncationHandler 发现“foo”在“bar”之后立即被调用,它会做一些特殊的事情。

You may be interested in wrapping the whole class inside a Proxy and watch it with an InvocationHandler:

http://www.javalobby.org/java/forums/t18631.html

Your InvocationHandler would do something special if it sees that "foo" is called immediatly after "bar", I guess.

旧街凉风 2024-12-13 04:38:45

看来您的意图是让应用程序代码检查方法实现,并在该方法无法在内部使用 try-catch 时进行条件分支。

除非您正在编写单元测试,否则我不鼓励这样做,原因有两个:

<强>1。开发人员应该了解他的应用程序逻辑。

您应该已经知道您的代码在做什么。如果该方法是
闭源API,请检查文档以了解抛出的异常类型。

<强>2。它增加了不必要的复杂性。

因为流量
执行取决于方法的实现,你将有一个
应用程序其行为取决于其自身状态
来源。
(例如,更改方法可能会产生副作用,其中
使调试变得更加困难。)

如果可以通过检查源代码或API文档来确定方法行为,那么为什么需要在运行时进行验证?

It seems like your intention is to have your application code check a method implementation, and conditional branch when that method fails to use try-catch internally.

Unless you are writing unit tests, let me discourage doing this for two reasons:

1. A developer should understand his application logic.

You should already know what your code is doing. If the method is part of a
closed-source API, check the documentation for thrown Exception types.

2. It adds unnecessary complexity.

Because flow of
execution depends on method implementation, you will have an
application whose behavior is dependent upon the state of its own
source.
(eg. Changing the method can create side-effects, which
makes debugging more difficult.)

If you can determine method behavior by checking the source code or API documentation, what is the need for verifying at run-time?

筱武穆 2024-12-13 04:38:45

据我所知,没有这样的反射 API 允许查看内部实现。您只能检查类中存在的方法,而不能检查方法中编写的逻辑。

As far as my knowledge is concern, there is no such reflection API which allows to see the inside implementations. You can only inspect the methods present in the Class, but can not the logic written in the method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文