Is there some nice way to check that some string represents a valid (fully qualified) Java class name? For example org.comPAny.ClassName
or even mYcRAZYcLASSnAME
are valid class names but something like org..package.MyClass
or org.ClassName.
are not. I want to check class name validity without loading that class.
Is there some convenient method in Java to check that? Or can you provide regular expression that is granted to cover all cases?
EDIT: Please do not suggest third party libraries.
A string is considered a valid identifier if it only contains alphanumeric letters (a-z) and (0-9), or underscores (_). A valid identifier cannot start with a number, or contain any spaces.
In order to qualify as a valid identifier, the string must satisfy the following conditions: It must start with either underscore(_) or any of the characters from the ranges ['a', 'z'] and ['A', 'Z']. There must not be any white space in the string.
A valid identifier must have characters [A-Z] or [a-z] or numbers [0-9], and underscore(_) or a dollar sign ($). for example, @javatpoint is not a valid identifier because it contains a special character which is @. There should not be any space in an identifier. For example, java tpoint is an invalid identifier.
To check if a string is a valid keyword, use the IsValidIdentifier method. The IsValidIdentifier method checks whether the entered value is an identifier or not. If it's not an identifier, then it's a keyword in C#.
The proper way to do this is to use javax.lang.model.SourceVersion.isName method (part of Java standard library).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With