4

I have a variable declared as type Object a which actually refers an instance of type A.

In EL, I can directly use the following expression to print the name property of type A:

${a.name}

How does it work?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
user705414
  • 20,472
  • 39
  • 112
  • 155
  • 1
    It's not JSTL, it's Expression Language(EL)....... – MD Sayem Ahmed Sep 21 '11 at 11:02
  • Indeed, I removed the JSTL tag and fixed the terminology in the question. To learn what JSTL is check http://stackoverflow.com/tags/jstl/info and to learn what EL is check http://stackoverflow.com/tags/el/info. – BalusC Sep 22 '11 at 16:53

2 Answers2

4

EL uses reflection under the hoods, usually via javax.beans.Introspector API.

This is what it roughly does under the covers on ${a.name}.

// EL will breakdown the expression.
String base = "a";
String property = "name";

// Then EL will find the object and getter and invoke it.
Object object = pageContext.findAttribute(base);
String getter = "get" + property.substring(0, 1).toUpperCase() + property.substring(1);
Method method = object.getClass().getMethod(getter, new Class[0]);
Object result = method.invoke(object);

// Now EL will print it (only when not null).
out.println(result);

It does not convert/cast the type in any way.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
3

It's because name is a property of the object a, and probably the object is also a JavaBean (not to be confused with Enterprise JavaBean).

See here for Expression Language Documentation and here for a short tutorial.

MD Sayem Ahmed
  • 28,628
  • 27
  • 111
  • 178