Home > Enterprise >  Cannot import class file from Java project into another class file in the same project
Cannot import class file from Java project into another class file in the same project

Time:11-07

I have a Java Maven project in Eclipse (2021-09 (4.21.0)) and am trying to import a class called BaseTest.java into another class (ElementFetch.java) within the same project, but in a separate package. If you look at the screenshot below, you will see my import src.test.java.youtubeframework.BaseTest; statement and will note the error indicator on line 5. Regardless of the paths I specify:

import youtubeframework.src.test.java.youtubeframework.BaseTest;
import src.test.java.youtubeframework.BaseTest; 
import test.java.youtubeframework.BaseTest;
import java.youtubeframework.BaseTest;
import youtubeframework.BaseTest;
import BaseTest;

the import will not work. There is always an error which prevents the import from working.

Can anyone please tell me what I'm doing wrong!? I'm completely stumped and it's very frustrating!

Any tips would be greatly appreciated!

Thanks!

My Eclipse Project setup

CodePudding user response:

Your first problem is that you are using the source path for the class as if it was the package name. The correct package name should be youtubeframework. So you should (in theory) use import youtubeframework.BaseTest.

But the second problem is that your "main" Java code cannot depend on your "test" Java code. That is why import youtubeframework.BaseTest doesn't work.

In the Maven view of the world, the "test" tree is for code that is only used for testing the stuff in the "main" tree:

  • "test" classes can depends on "main" classes.
  • "main" classes cannot depend on "test" classes.

If you have a "test" class that is used by something in the "main" tree, then it is actually part of your application / library / whatever, and it should be in the "main" tree.

  • Related