如何检查class级名称是否有效?

Java中是否有方法检查字符串是否可以用作类名?

SourceVersion.isName可用于检查完全限定名称。

如果没有. 应该允许s,检查可以这样做:

 boolean isValidName (String className) { return SourceVersion.isIdentifier(className) && !SourceVersion.isKeyword(className); } 

很简单,使用Class.forName(String name)方法,可以用来测试它,如下所示:

 public static boolean classExists(String className) { try { Class.forName(className); return true; } catch(ClassNotFoundException ex) { return false; } } 

编辑:如果像dashrb所说的那样,你要求一种方法来确定一个String是否可以用作一个类名(而不是如果已经有一个类名),那么你需要的是一个组合我在上面发布的方法(由于你不能重复使用类的名称而翻转了布尔值),并结合检查以查看String是否是Java保留的关键字。 我最近遇到了类似的问题并为它制作了一个实用工具类,你可以在这里找到它。 我不会为你写它,但你基本上只需要添加一个检查!JavaKeywords.isKeyword(className)

编辑2:当然,如果您还要强制执行普遍接受的编码标准,您可以确保类名以大写字母开头,其中包含:

 return Character.isUpperCase(className.charAt(0)); 

编辑3 :正如Ted Hopp指出的那样,即使包含java关键字也会使类名无效,并且由于JavaKeywords在我的一个生产应用程序中使用,我已经制作了一个更新版本 ,其中包含方法containsKeyword(String toCheck) ,它还将检查对于这种可能性。 方法如下(请注意您也需要类中的关键字列表):

 public static boolean containsKeyword(String toCheck) { toCheck = toCheck.toLowerCase(); for(String keyword : keywords) { if(toCheck.equals(keyword) || toCheck.endsWith("." + keyword) || toCheck.startsWith(keyword + ".") || toCheck.contains("." + keyword + ".")) { return true; }//End if }//End for return false; }//End containsKeyword() 

我使用了MrLore友情提供的java关键字列表。

 private static final Set javaKeywords = new HashSet(Arrays.asList( "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "void", "volatile", "while" )); private static final Pattern JAVA_CLASS_NAME_PART_PATTERN = Pattern.compile("[A-Za-z_$]+[a-zA-Z0-9_$]*"); public static boolean isJavaClassName(String text) { for (String part : text.split("\\.")) { if (javaKeywords.contains(part) || !JAVA_CLASS_NAME_PART_PATTERN.matcher(part).matches()) { return false; } } return text.length() > 0; } 

呀 –

 Class.forName(String className); 

它返回与具有给定字符串名称的类或接口关联的Class对象。 并抛出Exceptions

 LinkageError - if the linkage fails ExceptionInInitializerError - if the initialization provoked by this method fails ClassNotFoundException - if the class cannot be located