java 如何检查类名是否有效?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13979172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:37:31  来源:igfitidea点击:

How to check if the class name is valid?

javaclassmethods

提问by Maxii

Is there a method in Java to check if a string can be used as a class name?

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

回答by fabian

SourceVersion.isNamecan be used to check fully qualified names.

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

If no .s should be allowed, the check can be done this way:

如果不允许.s,则可以通过以下方式进行检查:

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

回答by MrLore

Quite simply, with the Class.forName(String name)method, which can be used to test this as follows:

很简单,使用该Class.forName(String name)方法,可用于测试如下:

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

Edit: If, as dashrb said, you're asking for a way to determine if a String can be used as a class name (rather than if there already is a class by that name), then what you need is a combination of the method I posted above (with the booleans flipped, as you can't reuse class names), and in combination with a check to see if the String is a Java-reserved keyword. I had a similar problem recently and made a utility class for it which you can find here. I won't write it for you, but you basically just need to add in a check for !JavaKeywords.isKeyword(className).

编辑:如果,正如 dashrb 所说,您正在寻求一种方法来确定 String 是否可以用作类名(而不是如果已经有该名称的类),那么您需要的是我在上面发布的方法(翻转布尔值,因为你不能重用类名),并结合检查字符串是否是 Java 保留的关键字。我最近遇到了类似的问题,并为它制作了一个实用程序类,您可以在此处找到。我不会为你写它,但你基本上只需要添加一个检查!JavaKeywords.isKeyword(className)

Edit 2: And of course, if you want to also enforce generally accepted coding standards, you could just make sure that the class name starts with a capital letter with:

编辑 2:当然,如果您还想强制执行普遍接受的编码标准,您只需确保类名以大写字母开头:

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

Edit 3: As Ted Hopp points out, even containing a java keyword invalidates a class name, and as JavaKeywords is used in one of my production applications, I have made an updated versionwhich includes the method containsKeyword(String toCheck)which will also check for this eventuality. The method is as follows (please note you need the list of keywords in the class too):

编辑 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()

回答by tcb

I used the list of java keywords kindly offered by MrLore.

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

private static final Set<String> javaKeywords = new HashSet<String>(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;
}

回答by Subhrajyoti Majumder

yap -

呸——

Class.forName(String className);

It returns the Class object associated with the class or interface with the given string name. And throws Exceptions

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

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