25

Consider the following interface:

public interface I {
    default String getProperty() {
        return "...";
    }
}

and the implementing class which just re-uses the default implementation:

public final class C implements I {
    // empty
}

Whenever an instance of C is used in JSP EL scripting context:

<jsp:useBean id = "c" class = "com.example.C" scope = "request"/>
${c.property}

-- I receive a PropertyNotFoundException:

javax.el.PropertyNotFoundException: Property 'property' not found on type com.example.C
    javax.el.BeanELResolver$BeanProperties.get(BeanELResolver.java:268)
    javax.el.BeanELResolver$BeanProperties.access$300(BeanELResolver.java:221)
    javax.el.BeanELResolver.property(BeanELResolver.java:355)
    javax.el.BeanELResolver.getValue(BeanELResolver.java:95)
    org.apache.jasper.el.JasperELResolver.getValue(JasperELResolver.java:110)
    org.apache.el.parser.AstValue.getValue(AstValue.java:169)
    org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
    org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:943)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:225)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

My initial idea Tomcat 6.0 was too old for Java 1.8 features, but I was surprised to see Tomcat 8.0 is also affected. Of course I can work the issue around by calling the default implementation explicitly:

    @Override
    public String getProperty() {
        return I.super.getProperty();
    }

-- but why on earth a default method could be a problem for Tomcat?

Update: further testing reveals default properties can't be found, while default methods can, so another workaround (Tomcat 7+) is:

<jsp:useBean id = "c" class = "com.example.C" scope = "request"/>
<%-- ${c.property} --%>
${c.getProperty()}
5
  • 1
    My guess is introspection does not work with interfaces default methods ? I'm really interested in the answer :)
    – Gaël J
    Commented Feb 1, 2016 at 12:18
  • Did you try adding the annotation @FunctionalInterface ?
    – rickz
    Commented Feb 1, 2016 at 16:51
  • @rickz: no I didn't, for two reasons: 1 IRL, my interface has more than one method (thus is not eligible for being annotated), and 2 @FunctionalInterface has a different scope (almost never used together with default methods): normally no default implementation and lots of anonymous ones. I'm already sick of IntelliJ IDEA politely reminding I should annotate an interface with @FunctionalInterface each time I happen to declare a single-method interface =)
    – Bass
    Commented Feb 1, 2016 at 16:57
  • 4
  • 1
    Very useful tip about using getter methods. Also works with OpenLiberty (at least as of version 22).
    – dbreaux
    Commented May 18, 2022 at 17:24

2 Answers 2

9

You can work around this by creating a custom ELResolver implementation which handles default methods. The implementation I have made here extends SimpleSpringBeanELResolver. This is Springs implementation of ELResolver but the same idea should be the same without Spring.

This class looks for bean property signatures defined on interfaces of the bean and attempts to use them. If no bean prop signature was found on an interface it continues on sending it down the chain of default behavior.

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.access.el.SimpleSpringBeanELResolver;

import javax.el.ELContext;
import javax.el.ELException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * Resolves bean properties defined as default interface methods for the ELResolver.
 * Retains default SimpleSpringBeanELResolver for anything which isn't a default method.
 *
 * Created by nstuart on 12/2/2016.
 */
public class DefaultMethodELResolver extends SimpleSpringBeanELResolver {
    /**
     * @param beanFactory the Spring BeanFactory to delegate to
     */
    public DefaultMethodELResolver(BeanFactory beanFactory) {
        super(beanFactory);
    }

    @Override
    public Object getValue(ELContext elContext, Object base, Object property) throws ELException {

        if(base != null && property != null) {
            String propStr = property.toString();
            if(propStr != null) {
                Optional<Object> ret = attemptDefaultMethodInvoke(base, propStr);
                if (ret != null) {
                    // notify the ELContext that our prop was resolved and return it.
                    elContext.setPropertyResolved(true);
                    return ret.get();
                }
            }
        }

        // delegate to super
        return super.getValue(elContext, base, property);
    }

    /**
     * Attempts to find the given bean property on our base object which is defined as a default method on an interface.
     * @param base base object to look on
     * @param property property name to look for (bean name)
     * @return null if no property could be located, Optional of bean value if found.
     */
    private Optional<Object> attemptDefaultMethodInvoke(Object base, String property) {
        try {
            // look through interfaces and try to find the method
            for(Class<?> intf : base.getClass().getInterfaces()) {
                // find property descriptor for interface which matches our property
                Optional<PropertyDescriptor> desc = Stream.of(PropertyUtils.getPropertyDescriptors(intf))
                        .filter(d->d.getName().equals(property))
                        .findFirst();

                // ONLY handle default methods, if its not default we dont handle it
                if(desc.isPresent() && desc.get().getReadMethod() != null && desc.get().getReadMethod().isDefault()) {
                    // found read method, invoke it on our object.
                    return Optional.ofNullable(desc.get().getReadMethod().invoke(base));
                }
            }
        } catch (InvocationTargetException | IllegalAccessException e) {
            throw new RuntimeException("Unable to access default method using reflection", e);
        }

        // no value found, return null
        return null;
    }

}

You will then need to register your ELResolver in your application somewhere. In my case I am using Spring's java configuration so I have the following:

@Configuration
...
public class SpringConfig extends WebMvcConfigurationSupport {
    ...
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        ...
        // add our default method resolver to our ELResolver list.
        JspApplicationContext jspContext = JspFactory.getDefaultFactory().getJspApplicationContext(getServletContext());
        jspContext.addELResolver(new DefaultMethodELResolver(getApplicationContext()));
    }
}

Im not 100% sure on if thats the appropriate place to add our resolver but it does work just fine. You can also load the ELResolver in during javax.servlet.ServletContextListener.contextInitialized

Here is the ELResolver in reference: http://docs.oracle.com/javaee/7/api/javax/el/ELResolver.html

4
  • I haven't tried this yet, but if the default method is overridden, will this resolver return the overridden value or the default value? I would want it to return the overridden value.
    – battmanz
    Commented Feb 9, 2018 at 16:41
  • @battmanz My guess is that it should return the overwritten value. However I dont have a quick way to test this. If it doesnt then you could always change the behavior of the property resolver.
    – ug_
    Commented Feb 9, 2018 at 18:28
  • 1
    Doesn't work if default method belongs to interface implemented by parent class, i.e. BaseClass implements InterfaceWithDefaultMethod, ChildClass extends BaseClass, then this property is not found on an object of class ChildClass. You should replace base.getClass().getInterfaces() with ClassUtils.getAllInterfaces(base).
    – izogfif
    Commented Sep 21, 2021 at 5:10
  • Also doesn't work if the method being called returns null - replace return ret.get(); with return ret.orElse(null); to fix this.
    – Gareth
    Commented Oct 21, 2021 at 11:26
1

Spring 5 removed SimpleSpringBeanELResolver so the above answer no longer works, but turns out that the base class didn't really do anything anyway. Spring 5 version below with fixes to the issues discussed in the comments above (using XML config)

public class DefaultMethodELResolver extends ELResolver {

    @Override
    public Object getValue(ELContext elContext, Object base, Object property) throws ELException {

        if (base != null && property != null) {
            String propStr = property.toString();
            if(propStr != null) {
                Optional<Object> ret = attemptDefaultMethodInvoke(base, propStr);
                if (ret != null) {
                    // notify the ELContext that our prop was resolved and return it.
                    elContext.setPropertyResolved(true);
                    return ret.orElse(null);
                }
            }
        }

        return null;
    }

    @Override
    public Class<?> getType(ELContext elContext, Object o, Object o1) {
        return null;
    }

    @Override
    public void setValue(ELContext elContext, Object o, Object o1, Object o2) {

    }

    @Override
    public boolean isReadOnly(ELContext elContext, Object o, Object o1) {
        return false;
    }

    @Override
    public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext elContext, Object o) {
        return null;
    }

    @Override
    public Class<?> getCommonPropertyType(ELContext elContext, Object o) {
        return Object.class;
    }

    /**
     * Attempts to find the given bean property on our base object which is defined as a default method on an interface.
     * @param base base object to look on
     * @param property property name to look for (bean name)
     * @return null if no property could be located, Optional of bean value if found.
     */
    private Optional<Object> attemptDefaultMethodInvoke(Object base, String property) {
        try {
            // look through interfaces and try to find the method
            for(Class<?> intf : ClassUtils.getAllInterfaces(base.getClass())) {
                // find property descriptor for interface which matches our property
                Optional<PropertyDescriptor> desc = Stream.of(PropertyUtils.getPropertyDescriptors(intf))
                        .filter(d->d.getName().equals(property))
                        .findFirst();

                // ONLY handle default methods, if its not default we dont handle it
                if(desc.isPresent() && desc.get().getReadMethod() != null && desc.get().getReadMethod().isDefault()) {
                    // found read method, invoke it on our object.
                    return Optional.ofNullable(desc.get().getReadMethod().invoke(base));
                }
            }
        } catch (InvocationTargetException | IllegalAccessException e) {
            throw new RuntimeException("Unable to access default method using reflection", e);
        }

        // no value found, return null
        return null;
    }

    public static class CustomResolverListener implements ServletContextListener {

        public void contextInitialized(ServletContextEvent event) {
            var jspContext =  JspFactory.getDefaultFactory().getJspApplicationContext(event.getServletContext());
            jspContext.addELResolver(new DefaultMethodELResolver());
        }

        public void contextDestroyed(ServletContextEvent event) {
        }
    }
}

and then in web.xml

<listener>
    <listener-class>DefaultMethodELResolver$CustomResolverListener</listener-class>
</listener>
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.