Puzzle 20: What Is my class
Consider a program that prints the name of its class file:
Package Com.javapuzzlers;public class Me{public static void Main (string[] args) {System.out.println (Me.class.getName () . ReplaceAll (".", "/") + ". Class");}}
This program first obtains its class name ("Com.javapuzzlers.Me") and then replaces all occurrences of the string "." With "/" and appends the string ". Class" at the end. Speaking of which, you will think that the program will print "Com/javapuzzlers/me.class", but when you run the program, you will find that the actual print is "///////////////////.class", then what is this?
The problem is that String.replaceall accepts a regular expression as its first argument, rather than accepting a character sequence literal constant. The "." In the regular expression can match any single character, so each character in the class name is replaced with a slash, so the output above is printed.
So how do we just match the period symbol? The escape character sequence is mentioned in the previous puzzle, so the period in the regular expression must be preceded by a backslash to be escaped. Again, because the backslash character has a special meaning in the literal meaning of the string, it identifies the beginning of the escape character sequence, so the backslash itself must be escaped with another backslash, which produces an escape character sequence that generates a backslash in the literal meaning of the string, and the modified program is as follows:
Package Com.javapuzzlers;public class me{public static void Main (string[] args) { System.out.println ( Me.class.getName (). replaceall ("\ \", "/") + ". Class"); }}
To address this type of problem, version 5.0 provides a new static method, Java.util.regex.Pattern.quote. It takes a string as an argument and can add the required escape character, returning a regular expression string that exactly matches the input string. Following are the programs that use this method:
Package Com.javapuzzlers;public class me{public static void Main (string[] args) { System.out.println ( Me.class.getName (). ReplaceAll (Pattern,quote ("."), "/") + ". Class"); }}
Another problem with the program is that its correct behavior is platform-dependent, and not all file systems use a slash sign to separate the file name component of the hierarchy. To get a valid file name on a running platform, use the correct platform-dependent delimiter symbol instead of the slash sign.
Java Puzzle characters (puzzle 20)