415

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.

Bozho
  • 554,002
  • 136
  • 1,025
  • 1,121
Federer
  • 30,291
  • 37
  • 89
  • 120

7 Answers7

531

There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.

Import one class and use the fully qualified name for the other one, i.e.

import com.text.Formatter;

private Formatter textFormatter;
private com.json.Formatter jsonFormatter;
dbreaux
  • 4,709
  • 1
  • 20
  • 56
Bozho
  • 554,002
  • 136
  • 1,025
  • 1,121
  • 21
    That's the right answer and to that I'd only add what you have implied: no, there is no such aliasing syntax in Java. – Sean Owen Mar 15 '10 at 14:42
  • 21
    Is this still a limitation in Java 8? – HairOfTheDog May 14 '14 at 20:28
  • 9
    @HairOfTheDog Nope, unfortunately no import aliasing have been added in Java8 – AdrieanKhisbe Jun 05 '14 at 14:20
  • 15
    Yeah I agree with your comment linuxdan... Java has gone the way of the dinosaur in terms of updates to its syntax. – Kevin Parker Feb 09 '15 at 02:27
  • And how would you resolve that particular case if you were to design a language? – Bozho Feb 15 '15 at 13:51
  • 6
    @Bozho The way python does: `import [fully-qualified-name] as [ident]`. The “as” keyword doesn’t seem to fit in Java as well, an alternative is approximately what C# uses: `import [ident] = [fully-qualified-name]`. – Daniel H Feb 16 '15 at 15:47
  • Yes, that was what the OP suggested. But I don't think it makes such a big difference :) – Bozho Feb 17 '15 at 14:38
  • 1
    It's better if you use fully qualified names for both classes when there are clashes like this. There is usually no good reason to prefer importing one over the other (maybe, if one is used 99.999% of the time, and the other one just once, you might prefer the import approach, but even then it's confusing). – Software Engineer Mar 09 '16 at 13:46
  • 5
    If my language A has a functionality that foreign language B misses: wow, how A is superior. If foreign language B has a functionality that A misses: meh, I don't get it why that's so important anyway... (yes, I'm talking about you, [Blub Paradox](http://www.paulgraham.com/avg.html)). – rsenna Mar 30 '16 at 13:19
  • @Bozho C# handles it like this: `using MyAlias = Full.Namespace.Path.To.Some.Class;` – Josh M. Jun 21 '18 at 15:14
  • 3
    Boo java. +1 for answer. – granadaCoder Aug 21 '18 at 16:40
  • I agree with @EngineerDollery, prioritizing one import over another creates ambiguity and confusion over what type "Formatter" refers to. I would use the fully-qualified names for each and abstract them into a third class. Call it something like `TextAndJSONFormatter`. – Braden Best Apr 21 '19 at 17:21
  • 1
    Instead in kotlin its implemented, and I will switch my spring project to kotlin for this and huge of another reasons – Tigran Babajanyan May 03 '19 at 03:59
77

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

siegi
  • 4,769
  • 1
  • 28
  • 40
  • 25
    wow! you weren't kidding about "not (...) anytime soon", I see that the feature request was dismissed as pointless sugar as far back as 1998! And every attempt to re-open the discussion during these past 18years have stranded on a reference to that ancient decision. I guess it would be easier to convince IDE-developers to implement this as a mask in the editor than to try to knock sense into Oracle. – Superole Sep 28 '16 at 13:43
  • 4
    The old reasoning is correct though -- in practice these clashes very seldom occur. – slim Oct 22 '16 at 18:53
  • 25
    I don't agree that these clashes rarely occur. Object orientation favors simple naming. I can have a class Employee from two different libraries that do separate things with an employee (for example). – Andrei Epure is hiring Mar 23 '17 at 14:59
  • 9
    @slim "_in practice these clashes very seldom occur_". It is not clear to me why these situations would occur less frequently in java (where you can have 10.000+ classes) than in other languages (where you usually have less classes) which _do_ support this "sugar" syntax. – Alain Pannetier May 21 '17 at 18:29
  • @AlainPannetier all I can say is, I've only experienced these clashes a handful of times in 15 years of Java programming. Yes, you can have 10,000+ classes in a project. But any given class should only need to reference a few. – slim May 22 '17 at 15:15
  • 32
    Absolutely incorrect. I'm facing a very simple scenario which is probably very common and where this syntactic sugar would be extremely helpful. Translation between related, but distinct object models (used in related but different products respectively) whose classes most of the time share the same name. The translation process requires you to refer to both classes in the same code block. In such a case (which must be very common), Java makes life very difficult. Just the number of views on this post should tell you the story. – hrshi1990 Jun 12 '17 at 06:30
  • 1
    And we have not yet considered static imports regarding the chance of clashing. Indeed static imports are not necessary as they can be simplified by qualifying with the simple declaring class name, but it's still inconvenient (depending on why you want to use static import in the first place). – SOFe Jul 15 '17 at 17:03
  • @slim - It's possible your assertion is true in the domains that you've worked in. I've also worked in a number of domains where I had no use for the ability to alias. However, in some domains, such as model-mapping/translation between models, as hrishirc mentions it is very common. As the service API's become more and more prevalent, model mapping will be an even larger part of our world. It is short-sighted to discard a legitimate feature request just because a person may not have experienced the need themselves. Language core versus business system integration are very different beasts. – Larry Hector Feb 27 '18 at 21:01
  • 1
    All the above, and that, maybe, just maybe, you don't want to have to type "com.company.library.project.component.class.fieldName" 50 times. – Keith Tyler Sep 13 '18 at 22:37
  • 1
    "In any event, it doesn't pass the bar of price/performance for a language change." - This pretty much summarizes why Java is so poorly designed. Scala for instance solved this LONG ago. – Arunav Sanyal Jun 15 '19 at 09:28
  • I don't think the main problem is the difficulty of implementation. I can't find the link at the moment, but I remember to have read somewhere about the problems of language changes (especially syntax changes) from one of the Java architects. They where similar in tone with the ones of Eric Lippert, one of the C# designers: "[_… just being a good feature is not enough_](https://blogs.msdn.microsoft.com/ericlippert/2008/10/08/the-future-of-c-part-one/)" or [this article](https://blogs.msdn.microsoft.com/ericlippert/2003/10/28/how-many-microsoft-employees-does-it-take-to-change-a-lightbulb/). – siegi Jun 18 '19 at 16:07
  • 2
    It's a constant burden for me that i encounter in every project and throughout my own common libraries. You have a 'Controller' that is in both server and client packages yet you are forced to name then ClientController and ServerController. I end up prepending the package name to every class so I end up with ControlButton, ControlTextBox, ControlListBox etc.. It's the only way around this very annoying problem. – LegendLength Jul 26 '19 at 13:34
  • 3
    If "these clashes very seldom occur" then this question wouldn't have so many upvotes from people wondering how to do it. – Ryan Lundy Oct 28 '19 at 13:50
  • I don't get the "price/performance for a language". There's a price, ok, but performance-wise? Why should it be so? Are the other JVM-targeting languages performance-impaired because they implement this aliasing? Even if Java is the exception rather than the norm! What about having to import 2 Article classes that could be renamed as, say, MagazineArticle and MaterialGood? But I don't even care about clashes: I want it for clarity or brevity. I'm not forced to use `article` for an instance of `Article`, so I shouldn't be forced to refer to that particular Article class with Article. – ShinTakezou May 01 '21 at 12:24
  • @ShinTakezou, I guess what the author wanted to express with "performance" is not (only) "speed" but rather "what you get from this language change". In other words: This changes impact on everyday use of the language is too small compared to its "cost" (e.g. increased complication of specification and learning effort for (new) users of the language, cost of implementation and future maintenance). – siegi May 01 '21 at 13:36
  • @siegi Learning efforts are 0: old-style Java guys can continue using imports the way they are used to: no one is forcing them to use any new backward-compatible feature of whatever language. The fact that other languages, even JVM-targeting ones, have the feature, what does it says about "cost of implementation and future maintenance"? Are you saying the other languages are plagued by "cost problems" because of that feature? Or that Java implementation is far more complicated, or delicate, and its maintainers don't take the risk lest they screw up? It's nonsense. – ShinTakezou May 02 '21 at 12:59
  • I encounter this if I use two different utility libraries e.g. `io.vavr.collection.List` and `java.util.List`. It's a shame Java does not have it yet. – Eponymous May 03 '21 at 14:16
67

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

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

MyCalendar myCalendar = new MyCalendar()
sfussenegger
  • 33,373
  • 14
  • 91
  • 117
24

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.

sepp2k
  • 341,501
  • 49
  • 643
  • 658
13

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

Chris Suszyński
  • 1,318
  • 14
  • 21
4

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;
kane
  • 4,242
  • 3
  • 31
  • 52
-6

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.

4thex
  • 863
  • 6
  • 19
  • 20
    This is a very poor solution. It completely fails to deal with statics, may require constant updates, and doesn't help with de/serialisation problems (such as deserialising from xml through jaxb). – Software Engineer Mar 09 '16 at 13:52