Java Package Import Alias(Java 包导入别名)
问题描述
在 Java 中是否可以导入包并为这个包导入一个特定的名称?
Is it possible in Java to import packages and give this package import a specific name?
我目前有一个类,它使用来自后端和服务包的一些 DTO.在这两个包中,DTO 具有相同的名称.而且我认为这不太可读:
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:
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.
Java 是否有类似 import com.backend.mypackage.a.b.c.d.UserDto as userDtoBackend
这样我可以缩短我的源代码?
Does Java have something like import com.backend.mypackage.a.b.c.d.UserDto as userDtoBackend
so i can shorten my source code?
推荐答案
不行,不能import x as y;"在 Java 中.
No, you can not do "import x as y;" in Java.
您可以做的是扩展类,或为其编写一个包装类,然后导入该类.
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) {
// ...
}
}
这篇关于Java 包导入别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 包导入别名


基础教程推荐
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 降序排序:Java Map 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01