简体   繁体   中英

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

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

So you must type Game.Wythoff

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/

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM