Reputation: 267267
I have a .jar which contains a class that I want to use: FooBar.class . This class is not in a package, its just sitting in the root directory of the .jar.
I've added the .jar to the project as a library, but the problem is, I don't know how to import it since its not in a package.
If I simply do: import FooBar;
I get the error: . expected
, and I'm not able to use FooBar
class anywhere since it says Symbol not found
.
Any ideas?
Upvotes: 3
Views: 1535
Reputation: 12123
I think you can do this with reflection.
Edit2:
Okay, perhaps you don't need reflection. I did another test where I instantiated Test directly and it worked. All you have to do is place the jar in your classpath, as the above poster said, without trying to import the class file.
Edit: Why the downvote? I was absolutely correct.
// No package statement here
public class Test {
public String getMessage() {
return "Hello World!";
}
}
$ javac Test.java
$ jar cvf my.jar Test.class
// No import statements needed
public class TestRefl {
public static void main(String[] args) throws Exception {
Class c = Class.forName("Test");
Test t = (Test) c.newInstance();
System.out.println(t.getMessage());
}
}
$ javac TestRefl.java
$ java -classpath ".:my.jar" TestRefl
$ Hello World!
You don't even have to import the class from the default package. And now you have an instance of it so you can do whatever you want.
Upvotes: 0
Reputation: 8586
You can't import from the default package. You (or whomever wrote it) shouldn't be using the default package anyway. You should avoid using the default package except for very small example programs.
If it's your code, put it in a package, as it should be. If it's someone else's, if they're taking the time to jar it up for you, they can put it in a package.
Alternatively, omit the import, but remember to add the jar to your classpath at compile time.
Alternatively, if you're lazy, and don't care about ignore all best practices (i.e. if this is a toy program, etc.)
$ jar -xvf <whatever>.jar
Will extract the files from the jar into the current directory, at which point you can use them as normal. If you're on Windows, you can probably do this via whatever program handles .zip files for you - a .jar is just a .zip with a manifest.
Upvotes: 4