Over a million developers have joined DZone.

Calling a Static Method From EL

· Java Zone

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

In my previous post I showed how to pass parameters in EL methods. In this post, I will describe how to call static methods from EL.

Step 1: Download Call.java and ELMethod.java

Download the classes Call.java and ELMethod.java, and copy them to your project.

Step 2: Add an instance of Call.java as an application scoped bean

There are many ways to do this, depending on this technology you are using. Here are some examples:

How to set request scope in JSP

request.setAttribute("call", new Call());  

How to set session scope in JSP

session.setAttribute("call", new Call()); 
How to set application scope from Servlet
this.getServletContext().setAttribute("call", new Call())  

How to set application scope from JSP

 <jsp:useBean id="call" class="Call" scope="application" />  

How to set application scope in Seam

Add these annotations to your class

@Name("call")
@Scope(ScopeType.APPLICATION)

Step 3: Call any static method from EL as follows

Let us say you have a static method which formats date.

   package com.mycompany.util;  

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtils {
public static String formatDate(String format, Date date) {
return new SimpleDateFormat(format).format(date);
}
}

You can call the above static method from EL as follows. Here “account” is a request scoped bean with a Date property call “creationDate”.

 ${call["com.mycompany.util.DateUtils.formatDate"]["MMM, dd"][account.creationDate]}  

In general the format is:

  ${call["full.package.name.MethodName"][arg1][arg2][...]}

Note:
  • Use map notation with [square brackets] when passing arguments to ${call}
  • First argument is the full package name + “.” + method name
  • If the static method you are calling takes arguments, simply pass those arguments using more [square brackets]
  • Overloaded methods are not supported, i.e. you cannot call methods where two methods with the same name exist in the class

References

 

From http://www.vineetmanohar.com/2010/08/calling-static-methods-from-el/

Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}