我知道如何使用固定字符串在java中查找方法,
someClass.getMethod("foobar", argTypes);
但是有没有办法使用正则表达式而不是固定字符串来查找给定类上的方法?
使用的一个示例可能是,如果我想查找名为“foobar”或“fooBar”的方法。使用“foo[Bb]ar”等正则表达式将匹配这些方法名称中的任何一个。
最佳答案
您应该将正则表达式应用于 getDeclaredMethods () 反射方法(或者 GetMethods() 如果您只想要公共(public)方法)。
[警告:如果存在安全管理器,这两种方法都会抛出 SecurityException。]
您将其应用于 getDeclaredMethod() 返回的每个方法的每个名称,并且仅在集合中记住兼容的方法。
类似的东西!
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, ...
关于java - 我可以使用正则表达式来查找java中类的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/227287/