22

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?

Dirk Rother
  • 440
  • 1
  • 4
  • 18
  • 1
    I think it would be much simpler to give different classes, different names. ;) i.e. instead of aliasing the classes, rename them instead. – Peter Lawrey Mar 26 '15 at 07:53

2 Answers2

25

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) {
        // ...
    }
}
Rik Schaaf
  • 1,101
  • 2
  • 11
  • 30
folkol
  • 4,752
  • 22
  • 25
  • 2
    Yes that's definitely a way. But if you have over 100 dto's it is not suitable to implement such a wrapper class for every single one. – Dirk Rother Mar 26 '15 at 08:53
  • 7
    That is correct. But if you manipulate over 100 DTO:s in the same method, you might have other problems to sort out first :) – folkol Mar 26 '15 at 08:55
  • 8
    This isn't really a good approach. It's potentially a huge amount of work that may need constant updating and which will have difficulty addressing static methods. And, if for example, you're de/serialising from/to xml into jaxb generated classes it won't work at all (or any other form of de/serialisation). – Software Engineer Mar 09 '16 at 13:44
15

There is no way to do this in Java.

user253751
  • 57,427
  • 7
  • 48
  • 90