11

I want to import all the classes in a package at once, not one by one. I tried import pckName.*; but it's not working.

Example: I have class X in package name pack1.

package pack1;

public class X {
.
.
}

and I have class Y in the same package.

package pack1;

public class Y {
.
.
}

I don't want to have to import them like this:

import pack1.X;
import pack1.Y;

Why? Because my package (har!) has a lot of classes and it's annoying to add them one by one. Is there a way to import them all at once?

Matt Fenwick
  • 48,199
  • 22
  • 128
  • 192
asaf
  • 331
  • 2
  • 6
  • 21
  • 1
    `import pack1.*;` would work – PermGenError Feb 12 '13 at 09:43
  • import pack1.*; should work. Why are you saying it is not working? – Jayamohan Feb 12 '13 at 09:45
  • actually that what i thought , i tried to do that but the eclipse mark me a red line under the class name. and when i hover the mouse there is 1 option : "Explicity import pack1.X;" – asaf Feb 12 '13 at 09:46
  • might be a misconfiguration of eclipse – Syjin Feb 12 '13 at 09:49
  • 1
    I guess you are having the same class X or Y is defined in two different packages. – Jayamohan Feb 12 '13 at 10:04
  • It's usually considered bad practice to import by wildcard (import `pack1.*`). http://stackoverflow.com/questions/147454/why-is-using-a-wild-card-with-a-java-import-statement-bad – rds Nov 10 '15 at 13:21

1 Answers1

10

You should use:

import pack1.*;

Add this line to the classes from the other packages. E.g.:

package pack2;

import pack1.*;

public class XPack2 {
    // ...
    // X x = new X();
    // ...
}

Just make sure, that your classpath is correctly set.

Problems can arise, when you have 2 classes with the same name: pack1.X and pack2.X.

Then you should explicitly write fully qualified name of the class.

Ostap Andrusiv
  • 4,827
  • 1
  • 35
  • 38
  • how do i check if the classpath is correctly set? maybe that is the problem because the classes was originaly build outside the package, then i create the package and grabbed all the classes to the that package.. but how do i fix that? – asaf Feb 12 '13 at 09:53
  • 1
    If you develop in eclipse, check your ```Build Path```: Project properties --> Configure Build Path. Or simply select the project and click [Ctrl]+[Shift]+[O]. This will automatically resolve all import issues. – Ostap Andrusiv Feb 12 '13 at 09:57
  • I think the problem is that i created the classes outside the package and only then i grabbed them into the package. but how should i fix that? i dont want to create them again. – asaf Feb 12 '13 at 10:02
  • Just fix all the red bullets in eclipse. Add correct package declarations to all the classes and then organize imports. – Ostap Andrusiv Feb 12 '13 at 10:07