java.util.regex.Pattern has a method Map<String, Integer> namedGroups(). For some reason they decided to make it private, and so there is no way to obtain this very useful information! :(
I've tried accessing this information (read-only) with this helper class:
package java.util.regex;
import java.util.Collections;
import java.util.Map;
public class PatternHelper {
public static Map<String, Integer> getNamedGroups(Pattern pattern) {
return Collections.unmodifiableMap(pattern.namedGroups());
}
}
But Java8 complains with java.lang.SecurityException: Prohibited package name: java.util.regex.
How can I access this information (read-only)? maybe by reflection?
Update This program using reflection fails. Any idea?
import java.lang.reflect.Method;
import java.util.regex.Pattern;
public class Test50 {
public static void main(String[] args) throws Exception {
Pattern p = Pattern.compile("(?<word>\\w+)(?<num>\\d+)");
Method method = Pattern.class.getMethod("namedGroups"); // it fails with NoSuchMethodException: java.util.regex.Pattern.namedGroups()
method.setAccessible(true);
Object result = method.invoke(p);
System.out.println("result: " + result);
}
}
setAccessibleon theMethodjava. You could do this with reflection, but beware that you are then directly accessing the internals of classPattern, which is an ugly hack and which is not guaranteed to still work on future versions of Java.