Maxime Michel
Maxime Michel

Reputation: 615

Using java class from one package in main of another package (Same project)

I have two packages inside a project I'm working on in Java and I need to call a class from one package when I run the main of a class in the other package.

I have something that looks like the following:

Project JavaCode
    /src
        /fr.insalyon.tc.framework
            Main.java
            Gameplay.java
        /Game
            Wythoff.java

and the problem is that in the Wythoff.java file I call import fr.insalyon.tc.framework.Gameplay; but I get an error when I run Main.java that says it cannot find the class Wthoff.

Main.java and Gameplay.java both have package fr.insalyon.tc.framework; as their first line, Gameplay is an interface and Wythoff implements Gameplay to play a game. What main does is the following:

BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
nomClasse = in.readLine();
Class<?> votreClasse = Class.forName(nomClasse);  
JeuCombinatoire jeu = (JeuCombinatoire) votreClasse.newInstance();

and when I run Main and it prompts me to type the class name, typing Wythoff gives me a ClassNotFoundException

I don't know how to modify the project or packages to have this work together whilst keeping the current packages as they are, I don't want to have Wythoff.java in the default package, it needs to be in /Game

Upvotes: 2

Views: 556

Answers (3)

Dushmantha
Dushmantha

Reputation: 3051

You need to type either fr.insalyon.tc.framework.Game.Wythoff which is the fully qualified name. alternatively in your case you can type also Game.Wythoff because the class which contains main method is in immediate parent package. And please note that normally package name starts with a simple letter for example game not Game.

Upvotes: 0

Sanket Koladiya
Sanket Koladiya

Reputation: 55

Class.forName(nomClasse); requires a fully Qualified path of class name. Please change it nomClasse to (packgname.classname) & Improt Appropriat packages.

NOTE:- For More information read the Java Documentation Link:- https://docs.oracle.com/javase/8/docs/api/

Upvotes: 1

Oscar P&#233;rez
Oscar P&#233;rez

Reputation: 4397

Class.forName(nomClasse); requires a full class name, as stated in the docs.

So you must type Game.Wythoff

Upvotes: 2

Related Questions