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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling
  • Java’s Next Act: Native Speed for a Cloud-Native World

Trending

  • Fixing Common Oracle Database Problems
  • Unlocking AI Coding Assistants Part 1: Real-World Use Cases
  • Develop a Reverse Proxy With Caching in Go
  • It’s Not About Control — It’s About Collaboration Between Architecture and Security
  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 user avatar
Konstantin Plotnikov
·
Updated Oct. 02, 18 · Analysis
Likes (17)
Comment
Save
Tweet
Share
25.6K Views

Join the DZone community and get the full member experience.

Join For Free

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

  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling
  • Java’s Next Act: Native Speed for a Cloud-Native World

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!