簡體   English   中英

創建返回布爾值並遍歷for-each循環的方法數組

[英]Creating array of methods returning boolean and iterating through for-each loop

好的,所以我有一批返回booleantrue/false

private void saveChangesOnEditButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                        
        updateMainTabsAccess();
        updateUserPaymentTabPermissions();
        updateUserRegistrationTabPermissions();
        updateUserStudentsTabPermissions();
        updateUserFacultyTabPermissions();
        updateUserHomePermissions(); //saves any update made on existing user settings/permissions
        updateUserInformation(); // sasve any update made on existing user information such as username
    }  

我想知道是否可以通過for-each循環檢查每個方法的返回值。

我正在考慮創建一個private boolean isUpdateSuccessful()方法。

private boolean isUpdateSuccessful(){
    Boolean a = updateMainTabsAccess();
    Boolean b = updateUserPaymentTabPermissions();
    //........so on....
    Boolean result = (a && b &&...)
    return result;
}

問題是,我不知道是否可以將它們放在arraylist或component數組中,例如

ArrayList<Boolean> listOfMethods = new ArrayList<Boolean>(method1,method2..);

這樣我就可以通過for-each循環檢查每個

for(Boolean b:listOfMethods){
    Boolean successful=true;
    successful =  (successful && b)
}

我的問題是:

1.)我如何提取這些方法的返回值並使用這些方法初始化Arraylist

2.)使用for-each循環,我嘗試執行的操作是否有可能? 我沒有,那你建議我做什么?

任何答復或建議,我將不勝感激。 我只是想檢查每種方法是否成功。 我想到使用?1:0:

提前致謝。

如果我是你,我會這樣做。 只是一個示例代碼:

private void saveChangesOnEditButtonActionPerformed(java.awt.event.ActionEvent evt) {
    if (updateMainTabsAccess()) {
        if (updateUserPaymentTabPermissions()) {
            if (updateUserRegistrationTabPermissions()) {
                ...
            } else {
                // error on update registration
            }
        } else {
            // error on update payment
        }
    }

具有以上樣式:

  • 當前一個方法失敗時,您不執行其他方法。
  • 可以為每個錯誤提供詳細的錯誤消息。
  • 您無需維護集合和迭代。

為什么不使用Stream來檢查結果:

Stream.<Boolean>of(updateMainTabsAccess(),
    updateUserPaymentTabPermissions(),
    updateUserRegistrationTabPermissions(),
    updateUserStudentsTabPermissions(),
    updateUserFacultyTabPermissions(),
    updateUserHomePermissions(),
    updateUserInformation()).allMatch(b -> b);

這樣,您無需進行短路評估,也無需為每種方法創建方法引用。

方法參考

List<Supplier<Boolean>> methods = Arrays.asList(this::updateMainTabsAccess,
                                                this::updateUserPaymentTabPermissions,
                                                ...
);

for (Supplier<Boolean> supplier : methods) {
    boolean methodResult = supplier.get();
    ...
}

但是,這幾乎不能認為是一種改進...

這將在您的類中找到所有方法,該方法在自動逐個調用方法並存儲對成功變量的響應后返回Boolean

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

public class Test {

    public static void main(String[] args) {
        Test test = new Test();
        Class c = test.getClass();      
        boolean successful = true; 
        for (Method method : c.getDeclaredMethods()) {
                if (method.getReturnType().toString().equals("boolean")) {
                    try {
                        String mname = method.getName();
                        Object o = method.invoke(test, null);
                        System.out.format("%s() returned %b%n", mname, (Boolean) o);
                        successful =  successful && (Boolean) o;

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
        }       
        System.out.println("final answer : " + successful);
    }

    public boolean a() {
        return true;
    }

    public boolean b() {
        return false;
    }

    public boolean c() {
        return false;
    }

}

希望對您有幫助。

如果您想執行每個方法並檢查每個方法是否成功,您可以簡單地編寫

boolean success = updateMainTabsAccess() &
    updateUserPaymentTabPermissions() &
    updateUserRegistrationTabPermissions() &
    updateUserStudentsTabPermissions() &
    updateUserFacultyTabPermissions() &
    updateUserHomePermissions() &
    updateUserInformation(); 

您已經收到一些答案。 如果您使用的是Java 8,那么Fabian就是一個很好的選擇。

但是要直接回答你的觀點

1.)我如何提取這些方法的返回值並使用這些方法初始化Arraylist。

    ArrayList<Boolean> resultsList = new ArrayList<Boolean>();

    resultsList.add(updateMainTabsAccess());
    ...

2.)使用for-each循環,我嘗試執行的操作是否有可能? 我沒有,那你建議我做什么?

    boolean res = true;

    for (Boolean singleResult : resultsList) {
        res = res && singleResult;
    }

當Java 8未引入Lambda時,這是實現目標的一種舊方法。

public class TestMethodsListCall {

    public abstract class Checker {
        public abstract boolean check();
    }

    public static void main(String[] args) {
        new TestMethodsListCall();
    }

    public TestMethodsListCall() {
        final TestMethodsListCall that = this;
        List<Checker> checkers = Arrays.asList( //
                new Checker() { public boolean check() { return that.methodA(); } }, //
                new Checker() { public boolean check() { return that.methodB(); } }  //
                // , ...
        );

        boolean res = true;
        for (Checker c : checkers) {
            res = res & c.check();
            if (!res) {
                // Break, display some message or all together
            }
        }
    }

    public boolean methodA() {
        return true;
    }

    public boolean methodB() {
        return false;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM