Home > Software engineering >  I'd like to import class for another project in Java
I'd like to import class for another project in Java

Time:01-23

(Thank you @MarkRotteveel !) I'm learning Java. I want to import class of another project. 'a' class('MySoup') in project A('recipe_nomodule') to project B('test')

However, there is no JRE System Library and it doesn't work. And I can't find posts about this problem

enter image description here ㄴ 1. I created another project. (recipe_nomodule)

  • and a package(recipe_nomodule) and also a class(MySoup)

enter image description here ㄴ 2. I created recipe.jar

enter image description here ㄴ 3. Java Build Path - Libraries - Add External JARs... (in Properties)

enter image description here ㄴ 4. result.

  • "MySoup cannot be resolved to a type"
  • "The type recipe_nomodule.MySoup is not accessible"

(23/01/2023 Thank you for the answers) enter image description here

enter image description here

CodePudding user response:

In the 'build path' settings of your new project (as per the screenshot you posted for item 3), add the other project in the 'project...' tab.

You don't need to make a jar, you don't need to add that jar via 'external libraries..'. You don't want to do that - you want the project dependency. That way, you can edit a file in either project, just save the file, and run, and see the updates, without having to go through the routine of making another jar. In debug mode, any change that doesn't affect signatures will even be instantly applied, no need to restart (only applies to long-running apps, of course).

Why doesn't your current approach work? Your question doesn't include enough information to be sure. A few options, based on the fact that key error message is 'not accessible':

  • You've explicitly told eclipse you don't want the package recipe_nomodule to be considered accessible by anything except the project that created it. I doubt you've done this.
  • It's set up as a module-based jar (with a module-info file), in which case, you'd have to export the package in the module-info.java file.
  • The class wasn't marked public at the time you made the jar file, even if it is now (this gets back to: Don't go via jar files, that way any updates won't propagate and that's very annoying).

More generally if you want to ship these concepts completely separately, you need to start answering questions about how you'd like your jar file to be distributed, you need to sign up with sonatype/mavencentral or some other entity that distributes open source, you need to learn maven, and more. Probably not worth getting into that, especially given that 'for fun' / 'for exercise' projects wouldn't be accepted.

  • Related