tags:

views:

568

answers:

2

I need a max function in my jstl, so i am writing a static function and exposing it in the tld as a jstl function.

The problem is, i dont know what type the arguments will be, int, long, double etc. Do i have to create a function for each data type? or Maybe i can just write the function for doubles, and pray that jstl will do the conversion for me?

edit2: nevermind, i thought the tld definition would be as simple as T max(T,T) but this is not the case. i have no idea how to make a tld definition for the generic method. I guess ill just pray that the jsp will convert my type correctly and use Math.max(double, double)

+2  A: 

Is it a max function like Math.max() (take two parameters, return the greater), or something like Arrays.sort() (take an array, return the greatest).

In the first case, JSP EL will coerce the arguments to the correct types if it is possible.

In the second case, a distinct method is needed for each primitive array component type you want to support.

erickson
its a math.max function. actually, i really wanted to use varags but it looks like jsp2.0 doesnt support those as jstl function arguments :P
mkoryak
+2  A: 

try this:

public static <T extends Comparable<? super T>> T max(T a, T b) {
    if (a.compareTo(b) > 0) {
        return a;
    } else {
        return b;
    }
}

public static void main(String[] args) {
    System.out.println(max(20, 10));
    System.out.println(max(103.2, 120.2));
    // it works even on strings...
    System.out.println(max("aaa", "bbb"));  
    // ... and booleans...
    System.out.println(max(true, false));  
}

in alternative you can use standard Java classes like Collections and Arrays:

Collections.max(Arrays.asList(10, 20, 30, 40, 50));
dfa
ill try that as soon as i figure out how to write a jslt function declaration for that =)
mkoryak