0

I would like to reference a class Bag in a JAR file, but Eclipse is telling me that Bag cannot be resolved to a type. I have added the JAR in which Bag is defined to the classpath for the project, but the error is still there. What am I doing wrong?

enter image description here

jds
  • 7,910
  • 11
  • 63
  • 101

2 Answers2

2

I think you can't do that, because the Bag class in algs4.jar is inside the default package. Before J2SE 1.4, we still can import classes from the default package using a syntax like this:

import Unfinished;

But from J2SE 1.5, that's no longer allowed. So if we want to access a default package class from within a packaged class requires moving the default package class into a package of its own. Read here for more detail explanation :

How to access java-classes in the default-package?

Some options you can choose :

  1. Access the class via reflection or some other indirect method. But it is a little bit hard, something like this :

    Class fooClass = Class.forName("FooBar"); Method fooMethod = fooClass.getMethod("fooMethod", new Class[] { String.class });

    String fooReturned = fooMethod.invoke(fooClass.newInstance(), new String("I did it"));

  2. If you own the source code of that jar library, you need to put it in properly package and wrap it again as a new jar library.

Community
  • 1
  • 1
the.wizard
  • 1,079
  • 1
  • 9
  • 25
  • @thewizard, thanks. This answer and others explain how what I am trying to do is wrong, but I don't see an explanation of what to do. What is a "non-default" package, and how can I import `algs4.jar` and `stdlib.jar` as non-default packages? – jds Nov 10 '14 at 12:37
  • update the answer for you, non-default package mean that other packages under src folder. If the 2 library was open source, you could download the sources, and setup a new project for both sources, then reference your project to these two projects. Hope this helps, please tick my answer if you think it is the best answer for your problems. Thanks. – the.wizard Nov 11 '14 at 03:31
  • @thewizard, thanks for the explanation. Since I am writing standalone classes for coursework, I opted to just put `WordNet` in the default package. Now I can reference `Bag` directly. – jds Nov 11 '14 at 13:27
0

You may need to either fully qualify the Bag class, or import it.

uberchris
  • 108
  • 5