Unable to use JAR in Eclipse - java

I have just created my first JAR in Eclipse, just a simple program with a single class Database.class. It is not in a package.
public class Database {
public Database() {
int dbInit = 1; } }
I have added it as an external JAR to the build path libraries for another project in Eclipse, but for some reason I cannot get Database db = new Database(), the default constructor, to work - it's as if the contents of the JAR are not being recognised.
Could anyone please offer any advice on this?
Thanks very much,
M

typically this works, so relax: you did some mistake and can fix it.
check content of your jar: run
jar vft myjar.jar
You should get output like
Database.class
Check that it is exactly what you get. Your class file must be at the root of the jar.
Verify that you are adding it to your second project correctly: Project/Properties/Java Build Path/Libraries, push button "Add external jars...", navigate to the jar and add it.
Now try to write in any java class of your project: Datab then push ctrl/space
It should complete to Database. Continue coding and enjoy.
BTW: why did you put your class to default package? I'd suggest you to put it into package. It will help you to avoid mistakes. for example probably you have other class named database in your code. How are you planning to resolve this conflict?

You might have to rebuild or clean your project.

The build path is not used at runtime. In your run configuration there's a tab to allow you to specify the classpath used when running the app.

Related

Question about groovy scripts recognition by IntelliJ IDEA

I guess by asking this I might sound a bit illegible, but I'm still unsure as to how to approach the problem.
In my spring project (not really my, work stuff) I've got some groovy scripts which are initially treated as resources, yet in reality they are rather the "source code" which is compiled not during the gradle assembly of the project but during the runtime by the application itself. And everything's fine with that.
The problem is that the IDE doesn't treat the groovy file properly. Dumb example to somehow describe what I mean:
import myproject.example.blabla
import groovy.transform.CompileStatic
#CompileStatic
class SomeClass1 implements SomeClass2 {
private final SomeClass2 someName1
SomeClass1() {
someName1 = new something
}
#Override
String getSmth() {
return someName1.getSmth()
}
}
The problems:
when I make "command + left_click" on SomeClass2, it says Cannot find declaration to go to, but when I press "command + O" it finds the file because it actually exists
.getSmth() is red, because Cannot resolve symbol
So it seems that I need to somehow show the dependencies via gradle to IDE only. Like, somehow specify the dependencies explicitly for IntelliJ IDEA so that it would understand that it is a source code as well and stop underlining everything with red.
Such files must be located in the module's Source Root directory for the IDE to recognize them as sources and so that navigation would also work.
In a Gradle-based project IDE configures Source Roots automatically based on the Gradle's Source Sets configuration. For each Gradle source set IDE creates a module with one Source Root directory.
So you must configure Gradle to create source set for the directories where these files are located: add them into default sources sets or create a custom source set for them.

using truezip in shadowJar built with gradle

i have a shadowJar compiled with gradle which uses truezip to get some files out of a zip-file.
i get this exception using it:
Exception in thread "main" java.util.ServiceConfigurationError: file (Unknown file system scheme! May be the class path doesn't contain the respective driver module or it isn't set up correctly?)
at de.schlichtherle.truezip.fs.FsAbstractCompositeDriver.newController(FsAbstractCompositeDriver.java:33)
at de.schlichtherle.truezip.fs.FsDefaultManager.getController0(FsDefaultManager.java:95)
at de.schlichtherle.truezip.fs.FsDefaultManager.getController(FsDefaultManager.java:78)
at de.schlichtherle.truezip.file.TBIO.getInputSocket(TBIO.java:280)
at de.schlichtherle.truezip.file.TFileInputStream.newInputStream(TFileInputStream.java:101)
at de.schlichtherle.truezip.file.TFileInputStream.<init>(TFileInputStream.java:95)
i set a archiveDetector like this:
final TArchiveDetector ad = new TArchiveDetector("foo", new ZipDriver(IOPoolLocator.SINGLETON));
TConfig.get().setArchiveDetector(ad);
the exception is thrown when i want to make an input-stream like this:
final TFileInputStream is = new TFileInputStream(thefile);
as far as i can tell the shadowJar contains all necessary classes, but maybe something is missing?
how would i know which class, which package is missing?
what else could cause this?
running it out of eclipse works...
thanks for any help.
That's a common issue when creating an uber-JAR: The individual entries at META-INF/services/* need to get appended. However, by default, many tools simply overwrite them when creating the uber-JAR. As a result, the ServiceLoader class cannot find all necessary plugins (e.g. for file system drivers), which is what this exception is complaining about.
So you need to fix the configuration of the tool which creates your uber-JAR. If you are using Maven with the maven-shade-plugin, then you can simply add the ServicesResourceTransformer - see https://maven.apache.org/plugins/maven-shade-plugin/examples/resource-transformers.html#ServicesResourceTransformer.
Another option is to not use an uber-JAR at all, which is the default when using Maven.
Eclipse can read Maven projects and establish its meta data from it, so maybe you want to consider converting your project to use Maven - if you haven't already.
I had the same problem. After some research i found the following solution:
In your build.gradle add the following:
shadowJar {
mergeServiceFiles()
}

Unable to find main class :bootRepackage

I got a problem with my gradle build. I use the standard proposed by the Spring Website (https://spring.io/guides/gs/rest-service/), but when I try to use gradle build, I got this error :
It doesnt work for this gradle, but when I use another one (that I took when I was at school) it work perfectly.
There are two possibilities
Your source directory is not in the right location (use the sourceSets directive to fix this. your source directory should resemble something like src/main/java/your/package)
Add this to indicate where your main class is
springBoot {
mainClass = "hello.FileUploader"
}
I am pretty sure it is 1.
I also have this problem, Here I solved the problem:
use org.springframework.boot:spring-boot-starter instead of org.springframework.boot:spring-boot-starter-web, if your project is only an module that will be used in other project.
Or Set the main class in gradle:
mainClassName = 'your.package.MainClass'
Or Just disable the bootRepackage
bootRepackage {
enabled = false
}
There is no main method in your project (otherwise the plugin would find one). A main method has a very specific signature, so check that you have public static void main(String[] args).
If the main class is not defined in the current project which the build.gradle file belongs to, but you want to launch it for some purpose, like sprint integration test. Do it like this:
Adding
bootRepackage {
mainClass = 'your.app.package.Application'
}
in build.gradle (after the line apply plugin: 'spring-boot', because the plugin needs to be loaded) fix the problem.
I know this is a very old post. But I came across this issue while trying to build my first spring- boot application (https://spring.io/guides/gs/spring-boot/#scratch).
So the location of the pom.xml, mentioned in the tutorial is incorrect. You need to place it outside your src folder.
So here is the final directory structure -
/workspace/src/main/java/hello/HelloController.java
/workspace/src/main/java/hello/Application.java
/workspace/pom.xml
I solved it by specifying the encoding. Probably it's because I wrote the code in an IDE.
java -Dfile.encoding=UTF-8 -jar build <filename>.jar
This happened to me as well.
I was confused by the location of build.gradle file: I thought it should be located in src/main/java/hello, because it is mentioned right after the instruction to create this sub-directory structure.
It should be placed in the root folder containing src folder. Once I did that and called "gradle build" from the root folder and not "./gradlew build" as the guide instructs, build was successful.
I did not perform the standard installation for gradle, just downloaded the binaries, maybe this is the reason that "./gradlew build" failed for me.

Running Junit tests in Eclipse, constantly getting "NoClassDefFoundError"

I added a new test class. And tried to run it, but got the no class def found error.
But other test classes work fine.
And I am sure the new test class is compiled, its .class file is in the right folder.
There isn't enough information in the question to provide a real answer.
The first step to debugging is to see if the .class file is really on the classpath, do something like,
Class c = SomeClass.class;
System.out.println(c.getResource(c.getSimpleName() + ".class"));
If you print something non null, then the .class file is on the classpath.
The second step is to make sure the NoClassDefFoundError is really being caused because the class you are loading does not exist. Use an eclipse exception breakpoint to break on NoClassDefFoundError, and see what class it is really trying to load. It may be that class X requires class Y to load.
problem solved by right clicking the project and then select maven->update project configurations.
But I still dont know what when wrong.
You get a NoClassDefFoundError if a class file was present at compile time, but is not available at runtime. So my recommendation is to check your class path, maybe a library or something else is missing for the new test.

How do you create a jar file of classes that can be re-used by multiple Android projects?

Here are the steps I have followed so far, with no luck. I am extremely new to Java projects so I suspect I may be missing something obvious.
Using Eclipse, I have created a simple Java project called TestSDK, created within that a package called com.test.testsdk, and within that the following class:
package com.test.testsdk;
public class TestClass {
public void TestMethod() {
}
}
This compiles without errors or warnings.
I then export this as a JAR file (TestSDK.jar) using Eclipse and the standard export options (export generated class files and resources, compress the contents of the JAR, generate manifest file). I have tried both sealing and not sealing the JAR which makes no difference.
I then create a new Android application project from File->New->Project in the Wizards list. This compiles and runs without warnings or errors on both the Android emulator and my test device (I get the hello world message).
I then add a reference to my TestSDK.jar file (using a variety of different methods as I will expand on shortly), import it into the main (and only) Android activity, and try to instantiate my TestClass and call TestMethod on it, like so:
package com.apptest.mobilesdktestapp;
import android.app.Activity;
import android.os.Bundle;
import com.test.testsdk.TestClass;
public class MobileSDKTestAppActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TestClass test = new TestClass();
test.TestMethod();
}
}
This compiles fine without warnings or errors. When trying to run it on the emulator or the device, however, I get the following error in my LogCat window:
AndroidRuntime Uncaught handler: thread main exiting due to uncaught exception
AndroidRuntime java.lang.NoClassDefFoundError: com.test.testsdk.TestClass
Searching the web for the NoClassDefFoundError results in a lot of suggestions on how to import the JAR file such that the class path is correct. As a result, I have tried all of the following methods of importing the JAR file:
"Add External JARs..." from the Libraries tab of Java Build Path in the project properties, followed by checking (or not checking, I tried both) the JAR in the Order and Export tab. Also tried moving the JAR to the top of the Order and Export list, which made no difference.
Creating a "libs" folder in the project, and adding the JAR there. I confirmed that the JAR is then also added to the "Android Dependencies" thing in the project list. Also tried right-clicking the JAR file and selecting Build Path->Add to Build Path which made no difference.
Moving the JAR into my Android Application project directory and doing "Add JARs..." instead of external JARs as in step 1, also all permutations of exporting or not and moving it to the top of the order list or not.
I have subsequently downloaded other 3rd party SDKs that are packaged as JAR files and included those in the very same Android application project, and those have all worked fine using any of the 3 methods above (I am able to instantiate classes from those SDKs and use them without error), which leads me to believe I am missing something or doing something wrong in my TestSDK project and/or class which is preventing it from being used in the Android Application project.
As I said, I am very new to Java, so I'm hoping it's something simple that I've overlooked. Any help or guidance would be appreciated.
If you are on R17 or higher version of the Android tools and ADT in Eclipse, then the first sentence of #2 is the correct answer; everything else listed in your question is unnecessary at best or harmful at worst.
I would recommend that you create a clean project, create the test activity, create the libs/ folder, copy the JAR into the libs/ folder, code to the JAR's API, compile, and run. If that works, then your original project still has stuff lingering around from your previous efforts that is causing you grief. If it fails, then something fairly strange is going on. The JAR itself is presumably fine, otherwise you would get compile errors.
I think I figured out what the issue was (or at least how to fix the issue, I'm still not 100% sure what I did)--
When I created the original TestSDK java project, I let it target the default JRE in the project creation dialog (jre7).
Checking the project properties of a new Android Application project, the Java Compiler section has "Compiler compliance level" set to 1.5. So, I tried recreating my TestSDK project again, but told it to use J2SE-1.5 as the execution environment instead of the defalut jre7.
After doing this, exporting the JAR and importing it to the Android project's libs directory, I am now able to instantiate the TestSDK classes and use them just fine without the NoClassDefFoundError exception.
Best guess is that the Android application was being compiled against an older version of the JRE than my TestSDK class (which I believe was targeting JavaSE-1.7), causing the issues. Matching the two versions up has solved it.

Categories