Can I use regular expressions to find a method on a class in java?

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.


Asked by: Max930 | Posted: 21-01-2022






Answer 1

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, ...

Answered by: Patrick487 | Posted: 22-02-2022



Answer 2

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; 
  }
}

Answered by: Wilson541 | Posted: 22-02-2022



Answer 3

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);
        }
    }

Answered by: Roman830 | Posted: 22-02-2022



Answer 4

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....

Answered by: Sawyer964 | Posted: 22-02-2022



Answer 5

When I want look for some method using simple name pattern I use this org.reflections

For example looking for some methods which are public and name start with get:

Set<Method> getters = ReflectionUtils.getAllMethods(SomeClass.class, ReflectionUtils.withModifier(Modifier.PUBLIC), ReflectionUtils.withPrefix("get"));

Answered by: Adelaide450 | Posted: 22-02-2022



Similar questions

regex - How do I tokenize input using Java's Scanner class and regular expressions?

Just for my own purposes, I'm trying to build a tokenizer in Java where I can define a regular grammar and have it tokenize input based on that. The StringTokenizer class is deprecated, and I've found a couple functions in Scanner that hint towards what I want to do, but no luck yet. Anyone know a good way of going about this?


JAVA: Build XML document using XPath expressions

I know this isn't really what XPath is for but if I have a HashMap of XPath expressions to values how would I go about building an XML document. I've found dom-4j's DocumentHelper.makeElement(branch, xpath) except it is incapable of creating attributes or indexing. Surely a library exists that can do this? Map xMap = new HashMap(); xMap.put("root/entity/@att", "fooattrib"); xMap.put("root/array[0]/ele/@at...


java - Regular expressions in J2ME

If I wanted to implement a regex engine in JavaME (Which lacks the regex libraries), where would be the best place to start? I'm imagining there is existing regex code out there which it would be possible to use as a starting point for porting. Failing that, a good guide on how to compile and execute a regular expression would do.


Are Java and C# regular expressions compatible?

Both languages claim to use Perl style regular expressions. If I have one language test a regular expression for validity, will it work in the other? Where do the regular expression syntaxes differ? The use case here is a C# (.NET) UI talking to an eventual Java back end implementation that will use the regex to match data. Note that I only need to worry about matching, not about extracting portions of th...


java - What is the effect of "*" in regular expressions?

My Java source code: String result = "B123".replaceAll("B*","e"); System.out.println(result); The output is:ee1e2e3e. Why?


java - Using Condition in Regular Expressions

Source: &lt;TD&gt; &lt;A HREF="/home"&gt;&lt;IMG SRC="/images/home.gif"&gt;&lt;/A&gt; &lt;IMG SRC="/images/spacer.gif"&gt; &lt;A HREF="/search"&gt;&lt;IMG SRC="/images/search.gif"&gt;&lt;/A&gt; &lt;IMG SRC="/images/spacer.gif"&gt; &lt;A HREF="/help"&gt;&lt;IMG SRC="/images/help.gif"&gt;&lt;/A&gt; &lt;/TD&gt; Regex: (&lt;[Aa]\s+[^&gt;]+&gt;\s*)?&lt;[Ii]...


java - How to use regular expressions to match everything before a certain type of word

I am new to regular expressions. Is it possible to match everything before a word that meets a certain criteria: E.g. THIS IS A TEST - - +++ This is a test I would like it to encounter a word that begins with an uppercase and the next character is lower case. This constitutes a proper word. I would then like to delete everything before that word. The example above should produce: Thi...


regex - Linkify text with regular expressions in Java

I have a wysiwyg text area in a Java webapp. Users can input text and style it or paste some already HTML-formatted text. What I am trying to do is to linkify the text. This means, converting all possible URLs within text, to their "working counterpart", i.e. adding &lt; a href="...">...&lt; /a>. This solution works when all I have is plain text: String r = "http(s)...


regex - How can I match a repeating pattern with Java regular expressions?

Given the following input string 3481.7.1071.html I want to confirm that The string has 1 or more numbers followed by a period. The string ends in html. Finally, I want to extract the left-most number (i.e. 3481). My current regex is nearly there but I can't capture the correct group: final Pattern p = Pattern.compile("(\\d++\\.)+html...


regex - Why do regular expressions in Java and Perl act differently?

My understanding is that Java's implementation of regular expressions is based on Perl's. However, in the following example, if I execute the same regex with the same string, Java and Perl return different results. Here's the Java example: public class RegexTest { public static void main( String args[] ) { String sentence = "This is a test of regular expressions."; System.out.pr...






Still can't find your answer? Check out these amazing Java communities for help...



Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)



top