jeudi 6 septembre 2018

Pass arguments of current executing function to other function dynamically

Snippet 1

public static String formatDateToString(BigDecimal param1, Date param2, String param3) {
    Utils.checkNullOrEmpty(?????); //I want the function params here dynamically

}

Snippet 2

public static boolean checkNullOrEmpty(Object...values){
    for(Object value: values){
        if(value==null){
            return true;
        }
        if(value instanceof String){
            String val = (String) value;
            if(val.isEmpty()){
                return true;
            }
        }
    }
    return false;
}   

How to dynamically get the arguments of the current function. (Refer Snippet1)

This will be helpful for functions with many parameters to avoid individual null checks.

I am able to get parameter types using

new Object(){}.getClass().getEnclosingMethod().getParameterTypes()

the disadvantage is it creates a new object and only gives my the types but not values.





Aucun commentaire:

Enregistrer un commentaire