如何在不使用方法字符串名称的情况下在Java中获取Method对象 [英] How to get Method object in Java without using method string names

查看:126
本文介绍了如何在不使用方法字符串名称的情况下在Java中获取Method对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找从方法中获取Method对象的便捷解决方法。想法:

I'm looking for a convenient workaround for getting the Method object from a method. The idea:

Method fooMethod = getMethod( new MyObject().foo() ) // returns method "foo" in MyObject

显而易见的方法是将方法的名称用作字符串:

The obvious way is to use the name of the method as a string:

Method fooMethod = MyObject.class.getMethod("foo")

但是我想避免这种情况,因为如果我重命名foo()代码将停止工作,或者我在所有使用它的地方重命名字符串。

but I want to avoid this because if I rename foo() that code will stop working or I have rename the string in all the places where it is used.

用例是我想使用类似于 ProperyChangeListeners 但是那些依赖于方法名称作为字符串。我想使用实际的方法(安全)而不依赖于字符串。

The use case is that I want to use something similar to ProperyChangeListeners however those rely on the method name as string. I'd like to use the actual method (safely) and not rely on strings.

我可以使用什么方法在重命名安全中获取方法 way?

What could I use to get the method in a rename safe way?

UPDATE
我想找到一个不依赖IDE功能的纯java解决方案

UPDATE: I'd like to find a pure java solution that does not rely on IDE features

推荐答案

实际上有一个库可以做到这一点:

There is actually a library that can do this:

Jodd MethRef - 强类型方法名称参考

Jodd MethRef - Strongly-typed method name references

https ://jodd.org/ref/methref.html

Methref<Str> m = Methref.on(Str.class);  // create Methref tool

// example #1
m.to().boo();
m.ref();                               // returns String: 'boo'

这篇关于如何在不使用方法字符串名称的情况下在Java中获取Method对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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