java 包别名,Java包导入别名

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) {

// ...

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值