Mag Musik
Mag Musik

Reputation: 1904

Using LambdaMetaFactory to expose getters causes class cast exception

I'm using LambdaMetaFactory to expose getters. I have a POJO with many fields and I don't know which fields are going to be populated. I'm trying to avoid both an extended if statement and also reflection.

So here's a snippet from my POJO:

@Data
@Builder
public class MyPojo {

private String email;

private String firstName;

private String lastName;

private String zipCode;

private String city;

private String street;

private String country;

...

    }

and here's my method which get's my values from all of the getters:

    public static String getValueFromGetterMethodName(String fieldName, MyPojo myPojo) {

    String methodName = constructGetterMethodName(fieldName);
    final MethodHandles.Lookup lookup = MethodHandles.lookup();
    MethodType getChangeDataMethodType = methodType(String.class, MyPojo.class);

    try {
        final CallSite site = LambdaMetafactory.metafactory(lookup, "apply", methodType(Function.class),
                methodType(Object.class, Object.class),
                lookup.findVirtual(MyPojo.class, methodName, methodType(String.class)),
                getChangeDataMethodType);

        Function<MyPojo, String> getterFunction = (Function<MyPojo, String>) site.getTarget()
                .invokeExact();
        return getterFunction.apply(myPojo);
    }
    catch (Throwable e) {
        log.error("Error getting getter method ref: " + e.getMessage());
        e.printStackTrace();
    }

    return null;
}

The problem is that this line here:

 Function<MyPojo, String> getterFunction = (Function<MyPojo, String>) site.getTarget()
                .invokeExact();

produces an Unchecked Class Cast warning. I know we're supposed to avoid those. This code works quite well. I'm not sure how to change it to avoid the class cast exception. CallSite doesn't accept parameters.

Upvotes: 0

Views: 252

Answers (0)

Related Questions