Vamsidhar
Vamsidhar

Reputation: 832

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.

Upvotes: 1

Views: 65

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074028

Java doesn't have the equivalent of JavaScript's arguments object, and reflection doesn't provide this information. But since the parameter list dictates what arguments you'll receive, just use the parameters directly:

public static String formatDateToString(BigDecimal param1, Date param2, String param3) {
    Utils.checkNullOrEmpty(param1, param2, param3);
}

Yes, this does mean repeating the parameter names, but you can't get around that.

Upvotes: 2

Related Questions