Java Reference
In-Depth Information
< Day Day Up >
Puzzle 21: What's My Class, Take 2
This program does exactly what the one in the previous puzzle did, but doesn't assume that the slash
character is used to separate filename components. Instead, the program uses
java.io.File.separator , which is a public String field specified to contain the platform-specific
filename separator. Does the program print the correct platform-specific name of the class file from
which it was loaded?
package com.javapuzzlers;
import java.io.File;
public class MeToo {
public static void main(String[] args) {
System.out.println(MeToo.class.getName().
replaceAll("\\.", File.separator) + ".class");
}
}
Solution 21: What's My Class, Take 2
The program displays one of two behaviors depending on the underlying platform. If the file
separator is a slash, as it is on UNIX, the program prints com/javapuzzlers/MeToo.class , which is
correct. If, however, the file separator is a backslash, as it is on Windows, the program prints
something like this:
Exception in thread "main"
StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:558)
at java.util.regex.Matcher.appendReplacement(Matcher.java:696)
 
 
Search WWH ::




Custom Search