views:

209

answers:

4

I know how to find a method in java using a fixed string,

someClass.getMethod("foobar", argTypes);

but is there a way to use a regular expression rather than a fixed string to find a method on a given class?

An example of the usage might be if I wanted to find a method that was called either "foobar" or "fooBar". Using a regular expression like "foo[Bb]ar" would match either of these method names.

+5  A: 

You should apply your regexp on getDeclaredMethods() reflection method (or GetMethods() if you want only the public ones).

[Warning: both methods will throw a SecurityException if there is a security manager.]

You apply it on each name of each method returned by getDeclaredMethod() and only memorize in a Collection the compliant Methods.

Something like!

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, ...
VonC
`getDeclaredMethods` may fail if you have a security manager installed. `getMethods` matches the question.
Tom Hawtin - tackline
I am not sure to follow you: 1/ both methods can trigger a SecurityException. 2/ How getMethods better matches the questions ? There is no reference to 'public' only methods... What I do follow is your downvote counter: 361 down-votes !??? really ? Impressive ;)
VonC
+1  A: 

Not directly. You could loop over all the methods and check each.

Pattern p = Pattern.compile("foo[Bb]ar");
for(Method m : someClass.getMethods()) {
  if(p.matcher(m.getName()).matches()) {
    return m; 
  }
}
sblundy
A: 

No, you can't do that, but you can get a list of the method a class has and apply the regexp to them.

Method[] getMethods( String regexp, Class clazz, Object ... argTypes ){
    List<Method> toReturn = new ArrayList<Method>();
    for( Method m : clazz.getDeclaredMethods() ){ 
         if( m.getName().matches( regExp ) ) { // validate argTypes aswell here...
             toReturn.add( m );
         }
    }
    return toReturn.toArray(); 
}

Well something like that....

OscarRyz
A: 

You could do it by iterating over ALL the methods on a class and matching them that way.

Not that simple, but it would do the trick

 ArrayList<Method> matches = new ArrayList<Method>();
 for(Method meth : String.class.getMethods()) {
  if (meth.getName().matches("lengt.")){
   matches.add(meth);
  }
 }
madlep