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

io.apicurio.registry.resolver.utils.Utils Maven / Gradle / Ivy

There is a newer version: 3.0.4
Show newest version
package io.apicurio.registry.resolver.utils;

import java.util.function.Consumer;

public class Utils {

    @SuppressWarnings("unchecked")
    public static  Class loadClass(String javaType) {
        try {
            return (Class) Thread.currentThread().getContextClassLoader().loadClass(javaType);
        } catch (ClassNotFoundException ignored) {
        }
        try {
            return (Class) Class.forName(javaType);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // TODO make the instantiation mechanism configurable
    @SuppressWarnings("unchecked")
    public static  void instantiate(Class type, Object value, Consumer setter) {
        if (value != null) {
            if (type.isInstance(value)) {
                setter.accept(type.cast(value));
            } else if (value instanceof Class && type.isAssignableFrom((Class) value)) {
                // noinspection unchecked
                setter.accept(instantiate((Class) value));
            } else if (value instanceof String) {
                Class clazz = loadClass((String) value);
                setter.accept(instantiate(clazz));
            } else {
                throw new IllegalArgumentException(
                        String.format("Cannot handle configuration [%s]: %s", type.getName(), value));
            }
        }
    }

    // TODO make the instantiation mechanism configurable
    public static  V instantiate(Class clazz) {
        try {
            return clazz.getConstructor().newInstance();
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy