如何使用java反射过滤方法

发布于 2024-12-20 02:11:58 字数 101 浏览 2 评论 0原文

我想从类中获取所有方法,但排除继承的方法,例如:wait、toString、hash 等。

是否有内置方法可以做到这一点,或者我是否需要定义一个黑名单并根据它检查方法名称?

I want to get all methods from a class but exclude the inherited methods such as : wait, toString, hash etc.

Is there a built in way to do it or do I need to define a blacklist and check the method name against it?

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

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

发布评论

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

评论(4

郁金香雨 2024-12-27 02:11:58

您可以忽略诸如

for(Method method: clazz.getMethods()) {
    if(method.getDeclaringClass() == Object.class) continue;

}

“注意:这将包括子类中重写的方法”之类的方法。

如果您不需要任何继承的方法,您可以使用

for(Method method: clazz.getDeclaredMethods()) {

You can ignore methods like

for(Method method: clazz.getMethods()) {
    if(method.getDeclaringClass() == Object.class) continue;

}

Note: this will include methods overridden in a sub-class.

If you don't want any inherited methods you can use

for(Method method: clazz.getDeclaredMethods()) {
深者入戏 2024-12-27 02:11:58

使用MyClass.getDeclaredMethods()

Use MyClass.getDeclaredMethods()

感情废物 2024-12-27 02:11:58

clazz.getDeclaredMethods() 将传递当前类定义的方法(从而有效地排除继承的方法)。然而,典型的模式是沿着类层次结构向上走
并排除来自 Object 的那些

clazz.getDeclaredMethods() will deliver methods defined by current class (and thus effectively exclude inherited ones). However, typical pattern is to walk up class hierarchy
and exlucde those coming from Object

丶视觉 2024-12-27 02:11:58

为此,您可以使用集合共享

您只需声明 w 谓词,然后使用:

CollectionUtils.filter(collection, predicate);

其中集合是方法包。
谓词是接受列表中元素的逻辑函数

You can use collection commons for this.

You will just have to declare w predicate and then use the:

CollectionUtils.filter(collection, predicate);

Where collection is the bag of methods.
Predicate is the logical function that accept the element on the list

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