DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption

Trending

  • PWA on iOS, Part 1: PWAs on the iPhone Are Older Than They Look
  • Taming Parameter Sniffing in SQL Server 2022 With PSP Optimization
  • Idempotency Under Concurrency: Why Your Application Check Isn't the Last Line of Defense
  • Giving AI Agents Safe Access to Legacy Systems: Introducing legacy2mcp

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Setters, Method Handles, and Java 11

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.

By 
Konstantin Plotnikov
·
Updated Oct. 02, 18 · Analysis
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
26.3K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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.

Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook