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

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

There is a newer version: 8.0.0-RC1
Show newest version
package net.hamnaberg.json.codec.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;

public interface Factory {
    A invoke(List params);

    static  Factory constructor(Class type, List params) {
        List> types = params.stream().map(Param::getType).collect(Collectors.toList());
        try {
            Constructor ctor = type.getConstructor(types.toArray(new Class[0]));
            return params1 -> {
                try {
                    return ctor.newInstance(params1.toArray());
                } 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.stream().map(Param::getType).collect(Collectors.toList());
        try {
            Method method = type.getDeclaredMethod(name, types.toArray(new Class[params.size()]));
            return params1 -> {
                try {
                    return (A)method.invoke(null, params1.toArray());
                } catch (Exception e) {
                    throw new RuntimeException(e.getMessage(), e);
                }
            };
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}