[java] Change Name of Import in Java, or import two classes with the same name

In Python you can do a:

from a import b as c

How would you do this in Java, as I have two imports that are clashing.

This question is related to java import

The answer is


It's probably worth noting that Groovy has this feature:

import java.util.Calendar
import com.example.Calendar as MyCalendar

MyCalendar myCalendar = new MyCalendar()

Today I filed a JEP draft to OpenJDK about this aliasing feature. I hope they will reconsider it.

If you are interested, you can find a JEP draft here: https://gist.github.com/cardil/b29a81efd64a09585076fe00e3d34de7


Java doesn't allow you to do that. You'll need to refer to one of the classes by its fully qualified name and only import the other one.


Actually it is possible to create a shortcut so you can use shorter names in your code by doing something like this:

package com.mycompany.installer;
public abstract class ConfigurationReader {
    private static class Implementation extends com.mycompany.installer.implementation.ConfigurationReader {}
    public abstract String getLoaderVirtualClassPath();
    public static QueryServiceConfigurationReader getInstance() {
        return new Implementation();
    }
}

In that way you only need to specify the long name once, and you can have as many specially named classes you want.

Another thing I like about this pattern is that you can name the implementing class the same as the abstract base class, and just place it in a different namespace. That is unrelated to the import/renaming pattern though.


It's ridiculous that java doesn't have this yet. Scala has it

import com.text.Formatter
import com.json.{Formatter => JsonFormatter}

val Formatter textFormatter;
val JsonFormatter jsonFormatter;

As the other answers already stated, Java does not provide this feature.

Implementation of this feature has been requested multiple times, e.g. as JDK-4194542: class name aliasing or JDK-4214789: Extend import to allow renaming of imported type.

From the comments:

This is not an unreasonable request, though hardly essential. The occasional use of fully qualified names is not an undue burden (unless the library really reuses the same simple names right and left, which is bad style).

In any event, it doesn't pass the bar of price/performance for a language change.

So I guess we will not see this feature in Java anytime soon :-P