tags:

views:

22

answers:

1

I'm writing a method that should extract the fully qualified class name out of a java.lang.reflect.Method-object. As i could not find any convenience method to get the classname of a Method-object, i'm trying to extract it with the following Regex-expression:

([A-Za-z.]*)[\(]

(maybe there's also a way without a Regex?).

public String getFullClassName(Method method) {
  // Example methodname:
  // public void com.test.user.impl.UserServiceImpl.deleteUser(java.lang.Long) throws com.test.user.api.exception.UserServiceException
  String methodName = method.toString();
  Pattern p = Pattern.compile("([A-Za-z.]*)[\\(]");
  Matcher m = p.matcher(methodName);
  String result = "";
  while (m.find()) {
      result = m.group();
  }
  return result;
}

Unfortunately, the Regex i built does not work correctly, as it gives me two result groups, but it should only give me one group. When i call the method with the Method

public void com.test.user.impl.UserServiceImpl.deleteUser(java.lang.Long) throws com.test.user.api.exception.UserServiceException

,i get two matching groups:

Group(0) = com.test.user.impl.UserServiceImpl.deleteUser(
Group(1) = com.testuser.impl.UserServiceImpl.deleteUser

so the method returns the first group "com.test.user.impl.UserServiceImpl.deleteUser(", but it should be "com.test.user.impl.UserServiceImpl.deleteUser". I don't want to choose the group manually, but i want a Regex that should already give me one matching group. Whats wrong with my Regex?

+2  A: 
String methodName = method.getDeclaringClass().getName() 

if you insist to use regex, here is the fix:

while (m.find()) {
    result = m.group(1);

    System.out.println(result);
}

group() or group(0) ALWAYS return the whole matched string. You need group(n) where n > 0 to get the value inside bracket.

However, I'd suggest that you are not using regex for this case.

nanda
Damn... i swear i also tried that without success ;) But know it works. Anyway, if anyone also has a fix for my regex it would be fine, just to know how i would write a matching regex when there would be no convenience method
ifischer
Thanks. Of course i'm not using the Regex now. But there must be a better regex which only gives me one group (without the opening brace)?
ifischer
You can try Pattern.compile("([A-Za-z.]*)"), but it will also give java.lang.Long and com.test.user.api.exception.UserServiceException
nanda