0

I'm using reflection to dynamically get class information specifically their method definitions. Here are some examples of the method definitions I'll be getting,

    "public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException"
    ...
    "public final native java.lang.Class<?> java.lang.Object.getClass()"

As you can see they're all unique, some have exceptions, parameters, etc. What would be the best way to parse through each string and get the method name?

My idea is that I could find the character ( and then backtrack until the first space saving a new string from that space to the ( character.

Will I run into a problem with this solution or is there an easier more elegant way to achieve what I want?

Update:

Each method declaration is contained in a separate string. This is a string problem rather than a reflection problem, I only mentioned reflection so you knew how I was getting this information dynamically. All I need to do is parse the string for the method name.

Kyle Bridenstine
  • 6,055
  • 11
  • 62
  • 100
  • Hmm, aren't you getting `Method` instance? If yes, why not just run `method.getName()`? – Dmitry Ginzburg Jul 24 '14 at 14:39
  • I suppose you aren't really using reflection for this, right? If you're parsing a Java file, you could use ANTLR. But, for a more appropriate answer, can you clarify your problem? – Carlos Melo Jul 24 '14 at 14:40
  • This might be of some help: http://stackoverflow.com/questions/442747/getting-the-name-of-the-current-executing-method – Madhusudan Joshi Jul 24 '14 at 14:40
  • I don't think I'm able to get the Method instance. I'm extracting all the information of a class using reflection. So I'm able to get field, constructor names but for the method it gives me the entire method declaration. – Kyle Bridenstine Jul 24 '14 at 14:41

1 Answers1

1

Your solution with brackets is okay (if you're really getting String, not java.lang.reflect.Method), I would suggest using regexes to write the code:

Pattern p = Pattern.compile("([^.]*)\\s*\\(");
Matcher m = p.match(str);
if (m.find()) {
    String methodName = m.group(1);
    //...
}

By the way, I don't understand why should you parse the String: where did you got it? The most common way to get the method in reflection is:

Class<?> clazz = ...
Method[] methods = clazz.getMethods();
// processing methods
for (Method method : methods) {
    // processing concrete method
    // for example, getting the name
    String name = method.getName();
}
Dmitry Ginzburg
  • 7,391
  • 2
  • 37
  • 48
  • I'm an idiot this was a simple reflection solution. I was using getMethods and calling toGenericString on them which gave me the method definition. Calling method.getName() solved my problem. Your answer is nice though because it still answers the string question. – Kyle Bridenstine Jul 24 '14 at 14:55