check And Extract Lambda Method using reflection - Java Lambda Stream

Java examples for Lambda Stream:Function

Description

check And Extract Lambda Method using reflection

Demo Code


//package com.java2s;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Optional;
import java.util.function.Function;

public class Main {
    public static Optional<Method> checkAndExtractLambdaMethod(
            Function function) throws ClassNotFoundException,
            InvocationTargetException, IllegalAccessException,
            NoSuchMethodException {
        Object serializedLambda = null;
        for (Class<?> clazz = function.getClass(); clazz != null; clazz = clazz
                .getSuperclass()) {//w  w w. java  2s . c  o  m
            Method replaceMethod = clazz.getDeclaredMethod("writeReplace");
            replaceMethod.setAccessible(true);
            Object serialVersion = replaceMethod.invoke(function);
            if (serialVersion.getClass().getName()
                    .equals("java.lang.invoke.SerializedLambda")) {
                Class.forName("java.lang.invoke.SerializedLambda");
                serializedLambda = serialVersion;
                break;
            }
        }
        if (serializedLambda == null) {
            return Optional.empty();
        }
        Method implClassMethod = serializedLambda.getClass()
                .getDeclaredMethod("getImplClass");
        Method implMethodNameMethod = serializedLambda.getClass()
                .getDeclaredMethod("getImplMethodName");
        String className = (String) implClassMethod
                .invoke(serializedLambda);
        String methodName = (String) implMethodNameMethod
                .invoke(serializedLambda);
        Class<?> implClass = Class.forName(className.replace('/', '.'),
                true, Thread.currentThread().getContextClassLoader());
        Method[] methods = implClass.getDeclaredMethods();
        Method parameterizedMethod = null;
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                parameterizedMethod = method;
            }
        }
        return Optional.of(parameterizedMethod);
    }
}

Related Tutorials