Don’t import wildcards from non-standard Java packages

Thursday, 22 July 2004

Import statements provide good documentation, but not if they contain wildcards. For example:

import com.zikzak.db.*;
import com.zikzak.util.*;


WidgetId = new WidgetId();

There’s no way to find out what package the WidgetId class belongs to without searching through the source tree. Much better to do this instead:

import com.zikzak.db.Table;
import com.zikzak.util.WidgetId;


WidgetId = new WidgetId();

Now it’s clear what and where WidgetId is.

This is not such a problem with well-known packages. For example, everybody knows what classes are in the java.util package, so this probably won’t cause any confusion:

import java.util.*;



You can leave a comment, or trackback from your own site.

  1. It appears as if, an explicit import without the wildcard is now REQUIRED for user defined classes(not using JAR files here). Why ? who knows ? Maybe SUN changed stuff in jdk 6.X

    So here:
    Even if there is no ambiguity and you reference WidgetId, as a wildcard

    import com.zikzak.db.*;
    //javac: won’t find the package //com.zikzak.db even if correctly written in //the javac -classpath methodology
    WidgetId = new WidgetId();//FAILS

    this will not compile(used javac -classpath properly).
    I am able to use 2 workarounds(still not using JAR methodology):

    1) You must restate the import as
    import com.zikzak.db.WidgetId;
    WidgetId = new WidgetId();//works

    OR explicitly in the instantiation declaration, as:

    2. //doesn’t make a difference now, if you //import it or not
    com.zikzak.db.WidgetId =
    new com.zikzak.db.WidgetId();

    I am compiling using the java compiler javac -classpath switch and it rejects any wildcard references to properly packaged up user defined class files, unless I did one of the above workarounds. The fact that these code workarounds actually work, is sufficient to let you know, there’s nothing wrong with my syntax of using the javac -classpath switch as they work, the moment I explicitly put the imports in the source code. Unfortunately, that also means you can’t use wild cards, on several classes belonging to your user defined package.

  2. Thank you. I looked EVRYWHERE to find out why my wildcard wasn’t working.

Leave a comment