Does EL automatically convert/cast the type? How does ${a.name} actually work?

前端 未结 2 1950
梦谈多话
梦谈多话 2021-01-06 06:40

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

2条回答
  •  粉色の甜心
    2021-01-06 07:17

    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:

    • Our EL wiki page
    • How to access objects in EL expression language ${}
    • Travesring through an object in java

提交回复
热议问题