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?
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.
If another class with the same name exists in another package, it will use the local class. Note that you can't import two classes with the same name in two different packages. The classes Integer and String belongs to the package java. lang but they don't need to be imported as the java.
Yes there is. You would need to implement your own Classloader and play some games to be able to access both during runtime.
If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface.
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.d.UserDto; public class ImportAlias { static class UserDtoAlias extends com.service.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) { // ... } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With