如何使用java反射过滤方法
我想从类中获取所有方法,但排除继承的方法,例如: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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以忽略诸如
“注意:这将包括子类中重写的方法”之类的方法。
如果您不需要任何继承的方法,您可以使用
You can ignore methods like
Note: this will include methods overridden in a sub-class.
If you don't want any inherited methods you can use
使用MyClass.getDeclaredMethods()
Use
MyClass.getDeclaredMethods()
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
为此,您可以使用集合共享。
您只需声明 w 谓词,然后使用:
其中集合是方法包。
谓词是接受列表中元素的逻辑函数
You can use collection commons for this.
You will just have to declare w predicate and then use the:
Where collection is the bag of methods.
Predicate is the logical function that accept the element on the list