Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Setters, Method Handles, and Java 11

DZone 's Guide to

Setters, Method Handles, and Java 11

Want to learn more about using setters, getters, and method handles? Check out this post where we explore the differences in implementing these methods in Java 11.

· Java Zone ·
Free Resource

When working the getters and setters in Java 8, it is natural to want to use BiConsumerand the Function interface instead of the direct method reflection (usually for greater performance).

I'm not alone in this desire, and there is even an article on DZone that discusses this approach. There are some open source projects (for example, here or here) that use similar methods to implement this functionality.

With so many examples out there, what could go wrong? Let’s create a utility class that implements setters and getters by copying the code from the article.

// The copy of the code from article https://dzone.com/articles/hacking-lambda-expressions-in-java
public class GettersSettersDzone {

    public static Function createGetter(final MethodHandles.Lookup lookup,
                                        final MethodHandle getter) throws Exception{
        final CallSite site = LambdaMetafactory.metafactory(lookup, "apply",
                MethodType.methodType(Function.class),
                MethodType.methodType(Object.class, Object.class), //signature of method Function.apply after type erasure
                getter,
                getter.type()); //actual signature of getter
        try {
            return (Function) site.getTarget().invokeExact();
        } catch (final Exception e) {
            throw e;
        } catch (final Throwable e) {
            throw new Error(e);
        }
    }

    public static BiConsumer createSetter(final MethodHandles.Lookup lookup,
                                          final MethodHandle setter) throws Exception {
        final CallSite site = LambdaMetafactory.metafactory(lookup,
                "accept",
                MethodType.methodType(BiConsumer.class),
                MethodType.methodType(void.class, Object.class, Object.class), //signature of method BiConsumer.accept after type erasure
                setter,
                setter.type()); //actual signature of setter
        try {
            return (BiConsumer) site.getTarget().invokeExact();
        } catch (final Exception e) {
            throw e;
        } catch (final Throwable e) {
            throw new Error(e);
        }
    }
}


Now, it is time to start testing. Firstly, we need to find metadata about the properties.

    private PropertyDescriptor nameProperty;
    private PropertyDescriptor valueProperty;

    @Before
    public void init() throws Exception {
        final BeanInfo beanInfo = Introspector.getBeanInfo(ResultDto.class);
        final Function<String, PropertyDescriptor> property = name -> Stream.of(beanInfo.getPropertyDescriptors())
                .filter(p -> name.equals(p.getName()))
                .findFirst()
                .orElseThrow(() -> new IllegalStateException("Not found: " + name));
        nameProperty = property.apply("name");
        valueProperty = property.apply("value");
    }

    public static class ResultDto {
        private double value;
        private String name;

        public double getValue() {return value;}
        public void setValue(double value) {this.value = value;}
        public String getName() {return name;}
        public void setName(String name) {this.name = name;}
    }


Let’s write a test for a getter:

    @Test
    public void testGetter() throws Exception {
        final ResultDto dto = new ResultDto();
        dto.setName("Answer");
        dto.setValue(42);
        final MethodHandles.Lookup lookup = MethodHandles.lookup();
        final Function nameGetter = GettersSettersDzone.createGetter(lookup,
                lookup.unreflect(nameProperty.getReadMethod()));
        final Function valueGetter = GettersSettersDzone.createGetter(lookup,
                lookup.unreflect(valueProperty.getReadMethod()));
        assertEquals("Answer", nameGetter.apply(dto));
        assertEquals(42.0, (double) valueGetter.apply(dto), 0.1);
    }


It works. Great! Let’s write a test for a setter:

    @Test
    public void testSetter() throws Exception {
        final ResultDto dto = new ResultDto();
        final MethodHandles.Lookup lookup = MethodHandles.lookup();
        final BiConsumer nameSetter = GettersSettersDzone.createSetter(lookup,
                lookup.unreflect(nameProperty.getWriteMethod()));
        final BiConsumer valueSetter = GettersSettersDzone.createSetter(lookup,
                lookup.unreflect(valueProperty.getWriteMethod()));
        nameSetter.accept(dto, "Answer");
        valueSetter.accept(dto, 42.0);
        assertEquals("Answer", dto.getName());
        assertEquals(42.0, dto.getValue(), 0.1);
    }


It works, again. Great! Thus, both our tests work in Java 8. Stop. Java 8. Java 11 is LTS starting from a few days ago.

Let’s test with Java 11. Getters still work great, but for setters, we receive the following error:

java.lang.invoke.LambdaConversionException: Type mismatch for instantiated parameter 1: double is not a subtype of class java.lang.Object

at java.base/java.lang.invoke.AbstractValidatingLambdaMetafactory.checkDescriptor(AbstractValidatingLambdaMetafactory.java:308)
at java.base/java.lang.invoke.AbstractValidatingLambdaMetafactory.validateMetafactoryArgs(AbstractValidatingLambdaMetafactory.java:294)
at java.base/java.lang.invoke.LambdaMetafactory.metafactory(LambdaMetafactory.java:311)
at samples.GettersSettersDzone.createSetter(GettersSettersDzone.java:32)
at samples.GettersSettersTest.testSetter(GettersSettersTest.java:53)


If we test some back history, the test also fails on Java 9.0.4, so the change came around the time of Java 9. Apparently, the implementation relied on some undocumented conversions, so it failed to work. There is a bug JDK-8174983 in progress that is related to this problem. We will possibly to have this problem fixed in Java 12 or, hopefully, in a version of Java 11.

I will skip my long and painful attempts to make it work. The pain was mostly because I did not understand that the method handles well. The final answer that I found was the following:

public class SettersJava11 {

    @SuppressWarnings("unchecked")
    public static BiConsumer createSetter(final MethodHandles.Lookup lookup,
                                          final MethodHandle setter,
                                          final Class<?> valueType) throws Exception {
        try {
            if (valueType.isPrimitive()) {
                if (valueType == double.class) {
                    ObjDoubleConsumer consumer = (ObjDoubleConsumer) createSetterCallSite(
                            lookup, setter, ObjDoubleConsumer.class, double.class).getTarget().invokeExact();
                    return (a, b) -> consumer.accept(a, (double) b);
                } else if (valueType == int.class) {
                    ObjIntConsumer consumer = (ObjIntConsumer) createSetterCallSite(
                            lookup, setter, ObjIntConsumer.class, int.class).getTarget().invokeExact();
                    return (a, b) -> consumer.accept(a, (int) b);
                } else if (valueType == long.class) {
                    ObjLongConsumer consumer = (ObjLongConsumer) createSetterCallSite(
                            lookup, setter, ObjLongConsumer.class, long.class).getTarget().invokeExact();
                    return (a, b) -> consumer.accept(a, (long) b);
                } else {
                    // Real code needs to support short, char, boolean, byte, and float according to pattern above
                    throw new RuntimeException("Type is not supported yet: " + valueType.getName());
                }
            } else {
                return (BiConsumer) createSetterCallSite(lookup, setter, BiConsumer.class, Object.class)
                        .getTarget().invokeExact();
            }
        } catch (final Exception e) {
            throw e;
        } catch (final Throwable e) {
            throw new Error(e);
        }
    }

    private static CallSite createSetterCallSite(MethodHandles.Lookup lookup, MethodHandle setter, Class<?> interfaceType, Class<?> valueType) throws LambdaConversionException {
        return LambdaMetafactory.metafactory(lookup,
                "accept",
                MethodType.methodType(interfaceType),
                MethodType.methodType(void.class, Object.class, valueType), //signature of method SomeConsumer.accept after type erasure
                setter,
                setter.type());
    }
}


In that version, we use interfaces that exactly match the signature of the setter method, and then we wrap them into BiConsumer using an object that is explicitly primitive to conversion.

The test for it works on both Java 11 and Java 8.

@Test
    public void testSetterJava11() throws Exception {
        final ResultDto dto = new ResultDto();
        final MethodHandles.Lookup lookup = MethodHandles.lookup();
        final BiConsumer nameSetter = SettersJava11.createSetter(lookup,
                lookup.unreflect(nameProperty.getWriteMethod()), nameProperty.getPropertyType());
        final BiConsumer valueSetter = SettersJava11.createSetter(lookup,
                lookup.unreflect(valueProperty.getWriteMethod()), valueProperty.getPropertyType());
        nameSetter.accept(dto, "Answer");
        valueSetter.accept(dto, 42.0);
        assertEquals("Answer", dto.getName());
        assertEquals(42.0, dto.getValue(), 0.1);
    }


So, projects that used method handles for accessing setters and getters could get some nasty surprises when running on Java 11. Referenced open source projects still use the old approach that would not work with primitives. I hope this article will help you to resolve these issues quickly.

The code for this article is available on GitHub.

Topics:
java ,reflection api ,getters ,setters ,method handles ,java 8 ,java 11

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}