我可以使用正则表达式在java中的类上查找方法吗?

Kev*_*vin 2 java reflection

我知道如何使用固定字符串在java中查找方法,

someClass.getMethod("foobar", argTypes);
Run Code Online (Sandbox Code Playgroud)

但有没有办法使用正则表达式而不是固定字符串来查找给定类的方法?

使用的一个例子可能是我想找到一个名为"foobar"或"fooBar"的方法.使用像"foo [Bb] ar"这样的正则表达式将匹配这些方法名称中的任何一个.

Von*_*onC 5

你应该在getDeclaredMethods()反射方法(或GetMethods()上应用你的正则表达式,如果你只想要公共的那样).

[警告:如果有安全管理器,这两种方法都会抛出SecurityException.

您将它应用于getDeclaredMethod()返回的每个方法的每个名称,并且只在Collection中记住兼容的方法.

就像是!

try
{
  final Pattern aMethodNamePattern = Pattern.compile("foo[Bb]ar");
  final List<Method> someMethods = aClass.getDeclaredMethods();
  final List<Method> someCompliantMethods = new ArrayList<Method>();
  for(final Method aMethod: someMethods)
  {
    final String aMethodName = aMethod.getName();
    final Matcher aMethodNameMatcher = aMethodNamePattern.getMatcher(aMethodName);
    if(aMethodNameMatcher.matches() == true)
    {
       someCompliantMethods.add(aMethod);
    }
}
catch(...) // catch all exceptions like SecurityException, IllegalAccessException, ...
Run Code Online (Sandbox Code Playgroud)