Prerna Rawat
Prerna Rawat

Reputation: 151

How to check if a class Exist in java project or not?

According to the requirement I have the name of class and I need to check whether this name of class is exist in a specific package or not. Here is my project structure:

app/entities/ <Classes>
app/contracts/CheckClass.java

I am writing following code in CheckClass.java and getting classNotFoundException in file. Here is my following code:

public boolean isClass(String className) {
   try {
        Class.forName(className.trim());
        return true;
    } catch (ClassNotFoundException e) {
        return false;
    }
}

Every-time I am getting ClassNotFoundException. I checked the className string which is passing correct class name. Is it because of different packages?

Upvotes: 0

Views: 1683

Answers (2)

bcsb1001
bcsb1001

Reputation: 2907

From the Javadoc:

Parameters:

className - the fully qualified name of the desired class.

A fully qualified class name is in the format package.class. An example is java.lang.System. Always look at the Javadoc.

According to your question, "I need to check whether this name of class is exist in a specific package or not" - I would add an if statement to check if className begins with the package string.

Upvotes: 0

dur
dur

Reputation: 16969

Your class name has to be full qualified, see Class#forName(String):

For example, the following code fragment returns the runtime Class descriptor for the class named java.lang.Thread:

Class t = Class.forName("java.lang.Thread")

In your case: app.contracts.CheckClass

Upvotes: 2

Related Questions