Java 包导入别名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29273362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:43:10  来源:igfitidea点击:

Java Package Import Alias

javasyntaximportpackage

提问by Dirk Rother

Is it possible in Java to import packages and give this package import a specific name?

是否可以在 Java 中导入包并给这个包导入一个特定的名称?

I currently have a class, which uses some DTO's from a backend and a service package. In both packages the DTO's have the same name. And I think this isn't quite readable:

我目前有一个类,它使用来自后端和服务包的一些 DTO。在这两个包中,DTO 的名称相同。而且我认为这不太可读:

com.backend.mypackage.a.b.c.d.UserDto userBackend = new com.backend.mypackage.a.b.c.d.UserDto();
com.service.mypackage.a.b.c.d.UserDto userService = new com.service.mypackage.a.b.c.d.UserDto();

mapper(userBackend, userService);

This is a small example. The class is actually quite complex and has a lot more code in it.

这是一个小例子。该类实际上非常复杂,其中包含更多代码。

Does Java have something like import com.backend.mypackage.a.b.c.d.UserDto as userDtoBackendso i can shorten my source code?

Java 有没有类似的东西,import com.backend.mypackage.a.b.c.d.UserDto as userDtoBackend所以我可以缩短我的源代码?

采纳答案by folkol

No, you can not do "import x as y;" in Java.

不,您不能执行“将 x 导入为 y”;在爪哇。

What you CAN do is to extend the class, or write a wrapper class for it, and import that one instead.

您可以做的是扩展该类,或为其编写一个包装类,然后导入该类。

import com.backend.mypackage.a.b.c.UserDto;

public class ImportAlias {
    static class UserDtoAlias extends com.backend.mypackage.a.b.c.d.UserDto {
    }

    public static void main(String[] args) {
        UserDto userBackend = new UserDto();
        UserDtoAlias userService = new UserDtoAlias();

        mapper(userBackend, userService);
    }

    private static void mapper(UserDto userBackend, UserDtoAlias userService) {
        // ...
    }
}

回答by user253751

There is no way to do this in Java.

在 Java 中没有办法做到这一点。