Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Package Import Alias [duplicate]

Tags:

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?

like image 703
Dirk Rother Avatar asked Mar 26 '15 07:03

Dirk Rother


People also ask

Does Java have import alias?

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.

Can Java import two classes with same name?

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.

Can we have two classes with same name under the same package?

Yes there is. You would need to implement your own Classloader and play some games to be able to access both during runtime.

Can we give fully qualified class name instead of importing that class?

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.


1 Answers

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) {         // ...     } } 
like image 83
folkol Avatar answered Sep 20 '22 09:09

folkol