开发者

Extract fully quallified classname out of a java.lang.reflect.Method-object with or without Regex

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);开发者_JAVA技巧
  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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜