1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | package Torello.Java; class ExtractTypeName { static String extract (final String srcFileName, final boolean throwOnBadTypeName) { final int LEN = srcFileName.length(); final int END_LEN; if (srcFileName.endsWith(".java")) END_LEN = 5; else if (srcFileName.endsWith(".class")) END_LEN = 6; else throw new IllegalArgumentException ("The File-Name passed is not a valid '.java' or '.class' File"); // Now, the following loop will search for the first instance of a forward or backwards // slash. If it doesn't find one before reaching the start of the String, the loop breaks // The loop start at the end of the String, and searches left-wards (towards the beginning) int pos = LEN - END_LEN - 1; while (pos >= 0) { final char c = srcFileName.charAt(pos); if (c == '\\') break; if (c == '/') break; pos--; } // If the loop reached the beginning of the String without finding any of the two standard // file-separators, then this "Source-File-Name" is a File-Name without any Directory-Path // Information. Use the entire-beginning of the input string! if (pos == -1) pos = 0; // Otherwise, make sure to "skip past" the actual File-Separator character! else pos++; // This is the computed string to return. It leaves off the beginning Directory Stuff (if // there were any), and it also leaves off the ending File-Suffix. final String ret = srcFileName.substring(pos, LEN - END_LEN); if (! StrSource.isValidJavaIdentifier(ret)) { if (throwOnBadTypeName) throw new JavaIdentifierException("You fucked up"); else return null; } return ret; } } |