Java 中, 是否有方法, 强制某 method 不接受 null 类型参数 ?
天蓬老师
天蓬老师 2017-04-18 10:34:33
0
2
472

让某 method 明确声明: 我不接受 null 参数, 传了 null , 我马上崩溃 !

并且, 该抛错在编译阶段抛出, 不要跑到运行时去

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(2)
PHPzhong

Java's type system does not support it and can only be implemented through plug-ins: Checker Framework, you need to add annotations and specify the plug-in during compilation.

The above implements the compiler's detection of null. As for the crash if null is passed, this can be achieved by inserting null check code through a plug-in.

巴扎黑

Good question. I usually only focus on how to implement functions, but I haven’t thought much about why Java doesn’t implement them this way, such as this question. It also evoked a lot of wild imagination in me. It would be great if Java syntax was supported. The development efficiency would be at least several times higher. But when I think about it again, something seems wrong.

NullPointerException is a runtime exception for a certain reason

Assuming Java supports such syntax, use annotation: @NotNullIndicate that the parameter is not empty

A scenario like this: After the user successfully logs in, update the user's login time and IP.

User data includes:

name password lasttime ip
aaa 123456 2017-01-09 192.168.1.1
bbb 123456 2017-01-08 192.168.1.1

Update user information pseudo code:

public void updateAccount(@NotNull Account account) {
    // 因为肯定不为空,可以放心大胆的更新Account的最新登录时间、ip
}

@NotNull表示参数:account means the parameter: account cannot be empty, there is no problem here.

Get user information to verify login pseudo code:

public Account login(String name) {
    // 1、连接数据库
    // 2、根据用户名获取Account
    // 3、验证用户信息
    // 4、验证成功返回Account信息,验证失败返回null
}

We just make sure that the parameters cannot be empty, and we don’t want the return value to be empty, so there is no problem.

Main logic judgment pseudo code:

public static void main(String[] args) {
    AccountService service = new AccountService();
    // aaa登录
    Account account = service.login("aaa","123456");
    service.updateAccount(account);
    
    // bbb登录
    Account account = service.login("bbb","123456");
    service.updateAccount(account);
    
    // ccc登录
    Account account = service.login("ccc","123456");
    service.updateAccount(account);
}

Then the question arises, whether the account parameter can be passed inservice.updateAccount()方法,编译能不能通过?从数据库中读取的Accoount对象本来就是个模凌两可对象,有可能代表某个人,也有可能是null.

Then make the return value non-null?

Yes, it can be like this. This becomes a pattern called NullObject Pattern , which means to create a dedicated empty object to represent that the result is empty.

Please check for details:

  • https://segmentfault.com/q/10...

  • http://www.cnblogs.com/haodaw...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template