Example usage for com.google.common.reflect Invokable from

List of usage examples for com.google.common.reflect Invokable from

Introduction

In this page you can find the example usage for com.google.common.reflect Invokable from.

Prototype

public static <T> Invokable<T, T> from(Constructor<T> constructor) 

Source Link

Document

Returns Invokable of constructor .

Usage

From source file:org.tensorics.core.util.SingleArgumentConstructorInstantiator.java

@Override
protected Invokable<R, R> invokableFor(Class<A> constructorArgumentClass) {
    try {// ww w . ja v a2  s  .  c om
        return Invokable.from(instanceClass.getConstructor(constructorArgumentClass));
    } catch (NoSuchMethodException | SecurityException e) {
        throw new IllegalArgumentException("The class '" + instanceClass
                + "' does not have a public constructor requiring exactly one argument of type '"
                + constructorArgumentClass + "'.", e);
    }
}

From source file:org.opendaylight.ovsdb.lib.schema.DatabaseSchema.java

protected <E extends TableSchema<E>> E createTableSchema(Class<E> clazz, TableSchema<E> table) {
    Constructor<E> declaredConstructor = null;
    try {//  w ww.  j av a  2s .c  o  m
        declaredConstructor = clazz.getDeclaredConstructor(TableSchema.class);
    } catch (NoSuchMethodException e) {
        String message = String
                .format("Class %s does not have public constructor that accepts TableSchema object", clazz);
        throw new IllegalArgumentException(message, e);
    }
    Invokable<E, E> invokable = Invokable.from(declaredConstructor);
    try {
        return invokable.invoke(null, table);
    } catch (Exception e) {
        String message = String.format("Not able to create instance of class %s using public constructor "
                + "that accepts TableSchema object", clazz);
        throw new IllegalArgumentException(message, e);
    }
}

From source file:org.tensorics.core.util.SingleArgumentFactoryMethodInstantiator.java

@SuppressWarnings("unchecked")
@Override/*from w  w  w. j a  va  2 s. c  o m*/
protected Invokable<R, R> invokableFor(Class<A> argumentClass) {
    for (Method method : instanceClass.getDeclaredMethods()) {
        if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers())
                && method.getReturnType().isAssignableFrom(instanceClass)
                && method.getParameterTypes().length == 1
                && method.getParameterTypes()[0].isAssignableFrom(argumentClass)) {
            return (Invokable<R, R>) Invokable.from(method);
        }
    }
    throw new IllegalArgumentException("No static factory method found in class '" + instanceClass
            + "' for argument type '" + argumentClass + "'");
}

From source file:io.ytcode.reflect.util.Example.java

private static void methods() {
    Methods ms1 = Scanner.paths("/io/ytcode/reflect/").scan().classes().methods();

    Methods ms2 = ms1.filter(new Predicate<Method>() {
        @Override//from w w  w.  jav  a2  s.c o m
        public boolean apply(Method m) {
            return Invokable.from(m).isPublic();
        }
    });
    System.out.println(ms2);

    Methods ms3 = ms1.modifiers(Modifier.PUBLIC, Modifier.STATIC);
    System.out.println(ms3);
}

From source file:net.derquinse.common.meta.InterfaceMetaBuilderFactory.java

private static <T extends WithMetaClass> MetaField<? super T, ?> checkReturnType(Method method,
        MetaField<? super T, ?> field, TypeToken<?> fieldType) {
    TypeToken<?> returnType = Invokable.from(method).getReturnType();
    // Check for primitive types
    if (Primitives.allPrimitiveTypes().contains(returnType.getRawType())) {
        returnType = TypeToken.of(Primitives.wrap(returnType.getRawType()));
    }/*  ww  w  .java 2  s . com*/
    if (returnType.isAssignableFrom(fieldType)) {
        return field;
    }
    return null;
}

From source file:io.ytcode.reflect.util.Example.java

private static void constructors() {
    Constructors cs1 = Scanner.paths("/io/ytcode/reflect/").scan().classes().constructors();

    Constructors cs2 = cs1.filter(new Predicate<Constructor<?>>() {
        @Override/* w w w  .  j  a v  a  2s  .co  m*/
        public boolean apply(Constructor<?> input) {
            return Invokable.from(input).isPublic();
        }
    });
    System.out.println(cs2);

    Constructors cs3 = cs1.modifiers(Modifier.PUBLIC);
    System.out.println(cs3);
}

From source file:edu.mit.streamjit.util.json.ToStringJsonifierFactory.java

/**
 * Finds the factory method or constructor to be used to construct Ts from
 * Strings./*from  w w w.  ja  v  a 2s . co m*/
 * @param <T> the type of the class
 * @param klass the class
 * @return a factory method or constructor, or null
 */
private static <T> Invokable<?, T> findFactory(Class<T> klass) {
    //The class must override toString().
    Method toString;
    try {
        toString = klass.getMethod("toString");
    } catch (NoSuchMethodException ex) {
        //Interfaces, maybe primitives, etc.
        return null;
    }
    if (!toString.getDeclaringClass().equals(klass))
        return null;

    //I'd like to condense these two loops into one loop over Invokeables,
    //but: 1) I want only static methods, but constructors are never
    //marked static; 2) Invokable hides the this argument to inner class
    //constructors, causing possible misdetection.
    for (Method method : klass.getDeclaredMethods()) {
        final int modifiers = method.getModifiers();
        if (!Modifier.isStatic(modifiers))
            continue;
        if (Modifier.isAbstract(modifiers))
            continue;
        if (!method.getReturnType().equals(klass))
            continue;
        Class<?>[] parameters = method.getParameterTypes();
        if (parameters.length != 1)
            continue;
        if (!parameters[0].isAssignableFrom(String.class))
            continue;
        if (!Modifier.isPublic(modifiers))
            try {
                method.setAccessible(true);
            } catch (SecurityException ex) {
                continue;
            }
        return Invokable.from(method).returning(klass);
    }
    for (Constructor<?> ctor : klass.getDeclaredConstructors()) {
        Class<?>[] parameters = ctor.getParameterTypes();
        if (parameters.length != 1)
            continue;
        if (!parameters[0].isAssignableFrom(String.class))
            continue;
        if (!Modifier.isPublic(ctor.getModifiers()))
            try {
                ctor.setAccessible(true);
            } catch (SecurityException ex) {
                continue;
            }
        //See the comment on Class.getConstructors(), which also applies to
        //Class.getDeclaredConstructors.
        @SuppressWarnings("unchecked")
        Constructor<T> ctorT = (Constructor<T>) ctor;
        return Invokable.from(ctorT);
    }
    return null;
}

From source file:ratpack.guice.ConfigurableModule.java

/**
 * Creates the configuration object.//from  www.j  av  a 2s.  c  o m
 * <p>
 * This implementation reflectively creates an instance of the type denoted by type param {@code C}.
 * In order for this to succeed, the following needs to be met:
 * <ul>
 * <li>The type must be public.</li>
 * <li>Must have a public constructor that takes only a {@link ServerConfig}, or takes no args.</li>
 * </ul>
 * <p>
 * If the config object cannot be created this way, override this method.
 *
 * @param serverConfig the application launch config
 * @return a newly created config object
 */
protected T createConfig(ServerConfig serverConfig) {
    TypeToken<T> typeToken = new TypeToken<T>(getClass()) {
    };

    if (typeToken.getType() instanceof Class) {
        @SuppressWarnings("unchecked")
        Class<T> clazz = (Class<T>) typeToken.getRawType();
        Factory<T> factory;
        try {
            Constructor<T> constructor = clazz.getConstructor(ServerConfig.class);
            factory = () -> Invokable.from(constructor).invoke(null, serverConfig);
        } catch (NoSuchMethodException ignore) {
            try {
                Constructor<T> constructor = clazz.getConstructor();
                factory = () -> Invokable.from(constructor).invoke(null);
            } catch (NoSuchMethodException e) {
                throw new IllegalStateException(
                        "No suitable constructor (no arg, or just ServerConfig) for module config type "
                                + typeToken);
            }
        }

        return Exceptions.uncheck(factory);
    } else {
        throw new IllegalStateException(
                "Can't auto instantiate configuration type " + typeToken + " as it is not a simple class");
    }
}

From source file:edu.mit.streamjit.util.bytecode.Method.java

public Invokable<?, ?> getBackingInvokable() {
    //We don't call this very often (if at all), so look it up every time
    //rather than burn a field on all Methods.
    Class<?> klass = getParent().getBackingClass();
    if (klass == null)
        return null;
    MethodType type = getType();/*from ww  w.ja va 2  s .  c om*/
    if (hasReceiver())
        type = type.dropFirstArgument();
    List<Class<?>> paramTypes = new ArrayList<>();
    for (RegularType t : type.getParameterTypes()) {
        Class<?> backingParamClass = t.getKlass().getBackingClass();
        //Live Methods can only have live Classes as parameter types.
        if (backingParamClass == null)
            return null;
        paramTypes.add(backingParamClass);
    }
    try {
        Class<?>[] array = paramTypes.toArray(new Class<?>[paramTypes.size()]);
        if (getName().equals("<init>"))
            return Invokable.from(klass.getDeclaredConstructor(array));
        else
            return Invokable.from(klass.getDeclaredMethod(getName(), array));
    } catch (NoSuchMethodException ex) {
        throw new AssertionError(String.format("Can't happen! Class %s doesn't have a %s(%s) method?", klass,
                getName(), paramTypes), ex);
    }
}

From source file:org.opendaylight.ovsdb.lib.jsonrpc.JsonRpcEndpoint.java

public void processRequest(Object context, JsonNode requestJson) {
    JsonRpc10Request request = new JsonRpc10Request(requestJson.get("id").asText());
    request.setMethod(requestJson.get("method").asText());
    logger.trace("Request : {} {}", requestJson.get("method"), requestJson.get("params"));
    OvsdbRPC.Callback callback = requestCallbacks.get(context);
    if (callback != null) {
        Method[] methods = callback.getClass().getDeclaredMethods();
        for (Method method : methods) {
            if (method.getName().equals(request.getMethod())) {
                Class<?>[] parameters = method.getParameterTypes();
                JsonNode params = requestJson.get("params");
                Object param = objectMapper.convertValue(params, parameters[1]);
                try {
                    Invokable from = Invokable.from(method);
                    from.setAccessible(true);
                    from.invoke(callback, context, param);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    logger.error("Unable to invoke callback " + method.getName(), e);
                }/* w  w  w  . jav  a  2 s. com*/
                return;
            }
        }
    }

    // Echo dont need any special processing. hence handling it internally.

    if (request.getMethod().equals("echo")) {
        JsonRpc10Response response = new JsonRpc10Response(request.getId());
        response.setError(null);
        String jsonString = null;
        try {
            jsonString = objectMapper.writeValueAsString(response);
            nettyChannel.writeAndFlush(jsonString);
        } catch (JsonProcessingException e) {
            logger.error("Exception while processing JSON string " + jsonString, e);
        }
        return;
    }

    // send a null response for list_dbs
    if (request.getMethod().equals("list_dbs")) {
        JsonRpc10Response response = new JsonRpc10Response(request.getId());
        response.setError(null);
        String jsonString = null;
        try {
            jsonString = objectMapper.writeValueAsString(response);
            nettyChannel.writeAndFlush(jsonString);
        } catch (JsonProcessingException e) {
            logger.error("Exception while processing JSON string " + jsonString, e);
        }
        return;
    }

    logger.error("No handler for Request : {} on {}", requestJson.toString(), context);
    return;
}