代码之家  ›  专栏  ›  技术社区  ›  Federer

在Java中更改导入的名称,或者导入同名的两个类

  •  287
  • Federer  · 技术社区  · 16 年前

    在python中,可以执行以下操作:

    from a import b as c
    

    你将如何在Java中这样做,因为我有两个冲突的导入。

    5 回复  |  直到 8 年前
        1
  •  373
  •   dbreaux    10 年前

    Java中没有导入别名机制。不能导入两个同名的类,并且不能同时使用这两个类。

    导入一个类并使用另一个类的完全限定名,即

    import com.text.Formatter;
    
    private Formatter textFormatter;
    private com.json.Formatter jsonFormatter;
    
        2
  •  47
  •   sfussenegger    11 年前

    值得注意的是 Groovy has this feature :

    import java.util.Calendar
    import com.example.Calendar as MyCalendar
    
    MyCalendar myCalendar = new MyCalendar()
    
        3
  •  43
  •   siegi The Coordinator    11 年前

    正如其他答案已经说明的,Java不提供这个特性。

    已多次请求实现此功能,例如 JDK-4194542: class name aliasing 或 JDK-4214789: Extend import to allow renaming of imported type .

    从评论中:

    这不是一个不合理的要求,虽然不是必要的。偶尔 使用完全限定名并不是一个不必要的负担(除非图书馆 真的重复使用相同的简单名称,左右,这是一个糟糕的风格)。

    在任何情况下,它都不能通过语言的价格/性能标准 改变。

    所以我想我们不会很快在Java中看到这个特性:-P

        4
  •  18
  •   sepp2k    16 年前

    Java不允许你这样做。您将需要按其完全限定名引用其中一个类,而只导入另一个类。

        5
  •  -3
  •   4thex    10 年前

    实际上,可以创建一个快捷方式,以便您可以在代码中使用较短的名称,方法如下:

    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();
        }
    }
    

    这样,您只需要指定一次长名称,就可以拥有所需的任意多个特别命名的类。

    我喜欢这个模式的另一点是,您可以将实现类命名为与抽象基类相同的名称,并将其放在不同的名称空间中。但这与导入/重命名模式无关。