All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.hamnaberg.json.codec.reflection.Factory Maven / Gradle / Ivy

package net.hamnaberg.json.codec.reflection;

import javaslang.collection.List;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public interface Factory {
    A invoke(List params);

    static  Factory constructor(Class type, List params) {
        List> types = params.map(Param::getType);
        try {
            Constructor ctor = type.getConstructor(types.toJavaList().toArray(new Class[params.size()]));
            return params1 -> {
                try {
                    return ctor.newInstance(params1.toJavaArray());
                } catch (Exception e) {
                    throw new RuntimeException(e.getMessage(), e);
                }
            };
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    @SuppressWarnings("unchecked")
    static  Factory factory(Class type, String name, List params) {
        List> types = params.map(Param::getType);
        try {
            Method method = type.getDeclaredMethod(name, types.toJavaList().toArray(new Class[params.size()]));
            return params1 -> {
                try {
                    return (A)method.invoke(null, params1.toJavaArray());
                } catch (Exception e) {
                    throw new RuntimeException(e.getMessage(), e);
                }
            };
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}