Thursday, June 29, 2023

Horror Code: Get Simple Class Name

 This article was posted originally on JRoller on January 29, 2014

You probably heard of one method of Class that give the simple name of the class, without all the packages. Even if you hadn't, you probably know a simple way to get the sub-String following the last dot. Well, I know someone who doesn't:


 	public static String classnameNormalize(String classname) {
		String s = new String(classname);
		int n;
		while (true) {
			n = s.indexOf(".");
			s = s.substring(n + 1, s.length());
			if (n == -1) {
				return s;
			} 
		} 
	} 
The function that gives the name of the class without its packages is Class.getSimpleName(). But if you don't know about it, and you need to get the substring after the last dot, it is better to use the String.lastIndexOf() method instead of this whole loop.


No comments:

Post a Comment