Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if string is a valid class identifier?

Tags:

java

class

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.

like image 573
Rasto Avatar asked Nov 26 '12 00:11

Rasto


People also ask

How do you check if a string is a identifier or not?

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.

How do you check if a string is a valid Java identifier?

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.

How do you know if a identifier is valid or invalid?

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.

How check string is valid or not in C#?

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#.


1 Answers

The proper way to do this is to use javax.lang.model.SourceVersion.isName method (part of Java standard library).

like image 66
abacabadabacaba Avatar answered Sep 22 '22 18:09

abacabadabacaba