在 Java 中返回多个值的最佳实践?

2022-01-19 00:00:00 function return java

今天,我在登录表单后面添加了额外的安全检查,以减缓暴力攻击.我有多个登录表单,并制作了一个易于调用的函数,该函数执行所有检查,然后返回结果.

Today I've added a extra security check behind my login forms, to slow down brute force attacks. I've got multiple login forms and made a nice easy to call function that does all the checking and then returns the result.

public static ValidateLoginResult validateLogin(HttpServletRequest request, String email, String password) {

问题是结果不是单个值,结果包括:

The problem is the result is not a single value, the result consists of:

boolean ok
String errorMessage
boolean displayCaptcha

为此,我创建了一个新类.这一切都很好.

For this I created a new class. This all works fine.

但我经常有方便的实用函数返回多个值,并且开始发现每次为结果创建一个新类有点烦人.

But I often have handy utility functions that return multiple values and start to find it a bit annoying to create a new class for the result every time.

有没有更好的方法来返回多个值?还是我只是懒惰?:)

Is there a better way of returning multiple values? Or am I just lazy? :)

推荐答案

不,这种结构在Java中是天生不存在的,但是你可以看看JavaTuples 库 可能适合您的需要并提供非常优雅的解决方案.使用 Triplet<Boolean, String, Boolean>

No, this kind of structure doesn't exists nativily in Java, but you can look at JavaTuples library that may suit your need and provide a quite elegant solution. Using a Triplet<Boolean, String, Boolean>

相关文章