Example usage for java.lang.reflect Method getParameterCount

List of usage examples for java.lang.reflect Method getParameterCount

Introduction

In this page you can find the example usage for java.lang.reflect Method getParameterCount.

Prototype

public int getParameterCount() 

Source Link

Usage

From source file:com.codeabovelab.dm.common.utils.PojoBeanUtils.java

/**
 * Copy properties into lombok-style builders (it builder do not follow java bean convention)
 * @param src source bean object//from   w  w  w .  j a v  a  2  s  .c o  m
 * @param dst destination builder object
 * @return dst object
 */
public static <T> T copyToBuilder(Object src, T dst) {
    PojoClass srcpojo = new PojoClass(src.getClass());
    Class<?> builderClass = dst.getClass();
    Method[] methods = builderClass.getMethods();
    for (Method method : methods) {
        boolean isBuilderSetter = method.getReturnType().equals(builderClass)
                && method.getParameterCount() == 1;
        if (!isBuilderSetter) {
            continue;
        }
        String propertyName = method.getName();
        Property property = srcpojo.getProperties().get(propertyName);
        if (property == null) {
            continue;
        }
        Object val = property.get(src);
        if (val == null) {
            continue;
        }
        try {
            method.invoke(dst, val);
        } catch (Exception e) {
            //nothing
        }
    }
    return dst;
}

From source file:org.apache.tinkerpop.gremlin.jsr223.JavaTranslator.java

private synchronized static void buildMethodCache(final Object delegate,
        final Map<String, List<Method>> methodCache) {
    if (methodCache.isEmpty()) {
        for (final Method method : delegate.getClass().getMethods()) {
            if (!(method.getName().equals("addV") && method.getParameterCount() == 1
                    && method.getParameters()[0].getType().equals(Object[].class))) { // hack cause its hard to tell Object[] vs. String :|
                List<Method> list = methodCache.get(method.getName());
                if (null == list) {
                    list = new ArrayList<>();
                    methodCache.put(method.getName(), list);
                }//from w  ww  .j  a  va 2  s.c o  m
                list.add(method);
            }
        }
        GLOBAL_METHOD_CACHE.put(delegate.getClass(), methodCache);
    }
}

From source file:io.coala.json.JsonUtil.java

public static <T> Class<T> checkRegisteredMembers(final ObjectMapper om, final Class<T> type,
        final Properties... imports) {
    for (Method method : type.getDeclaredMethods())
        if (method.getParameterCount() == 0 && method.getReturnType() != Void.TYPE
                && method.getReturnType() != type) {
            //            LOG.trace(
            //                  "Checking {}#{}(..) return type: {} @JsonProperty={}",
            //                  type.getSimpleName(), method.getName(),
            //                  method.getReturnType().getSimpleName(),
            //                  method.getAnnotation( JsonProperty.class ) );
            checkRegistered(om, method.getReturnType(), imports);
        }//from ww w  .  j a  v a  2s .c  o  m
    return type;
}

From source file:com.github.yongchristophertang.engine.java.LoggerProxyHelper.java

static Object addLogger(Logger logger, Method method, Object[] args, Object client) throws Throwable {
    if (method.getDeclaringClass() == Object.class) {
        return method.invoke(client, args);
    }// www.  j  av  a  2s. c o m

    String formatter = "\n\tAPI: " + method.getName() + "\n\n";
    formatter += "\tInput:\n";
    for (int i = 0; i < method.getParameterCount(); i++) {
        formatter += "\t\t" + method.getParameters()[i].getName() + " ("
                + method.getParameters()[i].getType().getSimpleName() + "): ";
        if (args[i] == null) {
            formatter += "NULL";
        } else if (args[i] instanceof Iterable) {
            int cnt = 0;
            Iterator iter = ((Iterable) args[i]).iterator();
            while (iter.hasNext()) {
                formatter += "\n\t\t\t[" + (++cnt) + "]: " + toPrinterString(iter.next(), false);
            }
        } else {
            formatter += toPrinterString(args[i], false);
        }
        formatter += "\n";
    }

    long bf = System.nanoTime();
    Object result;
    try {
        result = method.invoke(client, args);
    } catch (InvocationTargetException e) {
        formatter += "\n\tException: \n\t\t" + e.getTargetException();
        formatter += "\n=======================================================================\n";
        logger.info(formatter);
        throw e.getTargetException();
    }
    long af = System.nanoTime();

    formatter += "\n\tResponse Time(ms): " + (af - bf) / 1000000 + "\n\n\tOutput:\n";

    if (result == null) {
        formatter += "\t\tNULL\n";
    } else if (result instanceof Iterable) {
        Iterator iter = ((Iterable) result).iterator();
        int cnt = 0;
        while (iter.hasNext()) {
            formatter += "\t\t[" + (++cnt) + "]: " + toPrinterString(iter.next(), true) + "\n";
        }
        if (cnt == 0) {
            formatter += "\t\tEmpty Collection []\n";
        }
    } else {
        formatter += "\t\t" + toPrinterString(result, true) + "\n";
    }

    formatter += "=======================================================================\n";
    logger.info(formatter);
    return result;
}

From source file:com.yahoo.elide.core.EntityBinding.java

/**
 * Returns name of field whether public member or method.
 *
 * @param fieldOrMethod field or method//from  w  w w. j av a  2 s.c om
 * @return field or method name
 */
private static String getFieldName(AccessibleObject fieldOrMethod) {
    if (fieldOrMethod instanceof Field) {
        return ((Field) fieldOrMethod).getName();
    } else {
        Method method = (Method) fieldOrMethod;
        String name = method.getName();

        if (name.startsWith("get") && method.getParameterCount() == 0) {
            name = WordUtils.uncapitalize(name.substring("get".length()));
        } else if (name.startsWith("is") && method.getParameterCount() == 0) {
            name = WordUtils.uncapitalize(name.substring("is".length()));
        } else {
            return null;
        }
        return name;
    }
}

From source file:com.wrmsr.search.dsl.util.DerivedSuppliers.java

public static <T> Class<? extends Supplier<T>> compile(java.lang.reflect.Method target,
        ClassLoader parentClassLoader) throws ReflectiveOperationException {
    checkArgument((target.getModifiers() & STATIC.getModifier()) > 0);
    List<TargetParameter> targetParameters = IntStream.range(0, target.getParameterCount()).boxed()
            .map(i -> new TargetParameter(target, i)).collect(toImmutableList());

    java.lang.reflect.Type targetReturnType = target.getGenericReturnType();
    java.lang.reflect.Type suppliedType = boxType(targetReturnType);
    checkArgument(suppliedType instanceof Class);

    ClassDefinition classDefinition = new ClassDefinition(a(PUBLIC, FINAL),
            CompilerUtils.makeClassName(
                    "DerivedSupplier__" + target.getDeclaringClass().getName() + "__" + target.getName()),
            type(Object.class), type(Supplier.class, fromReflectType(suppliedType)));

    targetParameters.forEach(p -> classDefinition.addField(a(PRIVATE, FINAL), p.name,
            type(Supplier.class, p.parameterizedBoxedType)));
    Map<String, FieldDefinition> classFieldDefinitionMap = classDefinition.getFields().stream()
            .collect(toImmutableMap(f -> f.getName(), f -> f));

    compileConstructor(classDefinition, classFieldDefinitionMap, targetParameters);
    compileGetter(classDefinition, classFieldDefinitionMap, target, targetParameters);

    Class clazz = defineClass(classDefinition, Object.class, ImmutableMap.of(),
            new DynamicClassLoader(parentClassLoader));
    return clazz;
}

From source file:io.neba.core.resourcemodels.factory.ModelInstantiator.java

/**
 * @return all public methods annotated with @Inject. Fails if a public method
 * annotated with @Inject does not take exactly one argument.
 *//*w  w  w .  j av  a 2  s .c om*/
@Nonnull
private static ModelServiceSetter[] resolveServiceSetters(@Nonnull Class<?> modelType) {
    List<ModelServiceSetter> serviceSetters = new ArrayList<>();
    for (Method method : modelType.getMethods()) {
        if (isStatic(method.getModifiers())) {
            continue;
        }
        if (!annotations(method).containsName(INJECT_ANNOTATION_NAME)) {
            continue;
        }

        if (method.getParameterCount() != 1) {
            throw new InvalidModelException("The method " + method
                    + " is annotated with @Inject and must thus take exactly one argument.");
        }

        Filter filter = findFilterAnnotation(method.getParameterAnnotations()[0]);
        Type serviceType = method.getGenericParameterTypes()[0];
        ServiceDependency serviceDependency = new ServiceDependency(serviceType, modelType, filter);
        serviceSetters.add(new ModelServiceSetter(serviceDependency, method));
    }
    return serviceSetters.toArray(new ModelServiceSetter[0]);
}

From source file:org.dimitrovchi.conf.service.ServiceParameterUtils.java

public static String reflectToString(String name, Object proxy) {
    final Map<String, Object> map = new LinkedHashMap<>();
    for (final Method method : proxy.getClass().getMethods()) {
        if (method.getDeclaringClass() == Object.class || method.getDeclaringClass() == Proxy.class) {
            continue;
        }/*ww w  .  j a  v  a  2  s  .  c  om*/
        switch (method.getName()) {
        case "toString":
        case "hashCode":
        case "annotationType":
            continue;
        }
        if (method.getParameterCount() == 0) {
            try {
                map.put(method.getName(), method.invoke(proxy));
            } catch (ReflectiveOperationException x) {
                throw new IllegalStateException(x);
            }
        }
    }
    return name + map;
}

From source file:com.blurengine.blur.framework.ticking.TickMethodsCache.java

/**
 * Loads and caches a {@link Class}/*from   www  .  jav a2  s  . c  om*/
 *
 * @param clazz class to load and cache for future usage
 *
 * @return list of {@link TickMethod} represented the cached methods
 *
 * @throws IllegalArgumentException thrown if {@code clazz} is {@code Tickable.class}
 */
public static Collection<TickMethod> loadClass(@Nonnull Class<?> clazz) throws IllegalArgumentException {
    Preconditions.checkNotNull(clazz, "clazz cannot be null.");
    if (!LOADED_CLASSES.contains(clazz)) {

        Collection<TickMethod> tickMethods = CLASS_TICK_METHODS.get(clazz); // empty cache list, automatically updates

        { // Load superclasses first
            Class<?> superclass = clazz.getSuperclass();
            // No need for while loop as loadClass will end up reaching here if necessary.
            if (!superclass.equals(Object.class)) {
                tickMethods.addAll(loadClass(superclass));
            }
        }

        for (Method method : clazz.getDeclaredMethods()) {
            TickMethod tickMethod = getTickMethod(clazz, method);
            if (tickMethod != null) {
                tickMethods.add(tickMethod);
            } else {
                Tick tick = method.getDeclaredAnnotation(Tick.class);
                if (tick != null) {
                    try {
                        Preconditions.checkArgument(method.getParameterCount() <= 1,
                                "too many parameters in tick method " + method.getName() + ".");
                        if (method.getParameterCount() > 0) {
                            Preconditions.checkArgument(
                                    method.getParameterTypes()[0].isAssignableFrom(TickerTask.class),
                                    "Invalid parameter in tick method " + method.getName() + ".");
                        }
                        boolean passParams = method.getParameterCount() > 0;
                        // Tickables may be marked private for organisation.
                        method.setAccessible(true);

                        tickMethods.add(new TickMethod(method, passParams, tick));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        LOADED_CLASSES.add(clazz);
    }
    return Collections.unmodifiableCollection(CLASS_TICK_METHODS.get(clazz));
}

From source file:net.radai.beanz.util.ReflectionUtil.java

public static Method findGetter(Class<?> clazz, String propName) {
    Set<String> expectedNames = new HashSet<>(
            Arrays.asList("get" + propName.substring(0, 1).toUpperCase(Locale.ROOT) + propName.substring(1),
                    "is" + propName.substring(0, 1).toUpperCase(Locale.ROOT) + propName.substring(1) //bool props
            ));/* w  ww .  j ava2  s.c  o  m*/
    for (Method method : clazz.getMethods()) {
        String methodName = method.getName();
        if (!expectedNames.contains(methodName)) {
            continue;
        }
        if (method.getParameterCount() != 0) {
            continue; //getters take no arguments
        }
        Type returnType = method.getGenericReturnType();
        if (returnType.equals(void.class)) {
            continue; //getters return something
        }
        if (methodName.startsWith("is")
                && !(returnType.equals(Boolean.class) || returnType.equals(boolean.class))) {
            continue; //isSomething() only valid for booleans
        }
        return method;
    }
    return null;
}