Is it possible in Java to import packages and give this package import a specific name?
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.
Does Java have something like import com.backend.mypackage.a.b.c.d.UserDto as userDtoBackend so i can shorten my source code?
解决方案
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) {
// ...
}
}