Skip to content

Instantly share code, notes, and snippets.

@awwsmm
Last active August 18, 2018 16:43
Show Gist options
  • Save awwsmm/85575d2756f69b95564ff11b8ee105fd to your computer and use it in GitHub Desktop.
Save awwsmm/85575d2756f69b95564ff11b8ee105fd to your computer and use it in GitHub Desktop.
Unshuffle a Java method signature that's mis-ordered
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Signature {
public static void main(String[] args) {
// slightly more complex example to show off capabilities of method
String oldSignature = "synchronized static final native public void barFooer(int foo, double bar)";
// echo to user
System.out.printf("%nOriginal method signature:%n %s%n%n", oldSignature);
// group number ( 1 ) ( 2 ) ( 3 ) ( 4 ) ( 5 ) ( 6 ) ( 7 )
String regex = "(public|protected|private)|(abstract|static)|(final)|(volatile)|(synchronized)|(native)|(strictfp)";
// create regex.Pattern and regex.Matcher objects
Pattern pat = Pattern.compile(regex);
Matcher mat = pat.matcher(oldSignature);
// array to hold signature "groups" in correct order
String[] groups = new String[7];
// int to hold end of last matched group
int endOfLastGroup = -1;
while (mat.find()) {
for (int gg = 1; gg <= 7; ++gg) {
// get the new matched group and any previous match in this group
String newGroup = mat.group(gg);
String oldGroup = groups[gg-1];
// where does the new matched group end?
int endOfNewGroup = mat.end();
// did we find a new match in this group?
if (newGroup != null) {
// cannot have, for instance, both "public" and "private"
if (oldGroup != null) {
System.err.printf("Error! Signature cannot contain both '%s' and '%s'!%n", newGroup.trim(), oldGroup.trim());
return;
}
// otherwise, new group found!
groups[gg-1] = newGroup;
// find furthest-right matched group end
if (mat.end() > endOfLastGroup)
endOfLastGroup = mat.end();
} } }
// new signature will be constructed with a StringBuilder
StringBuilder newSignature = new StringBuilder("");
// add groups to new signature in correct order
for (String group : groups) {
if (group != null) {
newSignature.append(group.trim());
newSignature.append(" ");
} }
// finally, add the return type, method name, arguments, etc.
newSignature.append(oldSignature.substring(endOfLastGroup).trim());
// echo to user
System.out.printf("New method signature:%n %s%n%n", newSignature.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment