Example usage for java.lang.reflect Method getDeclaringClass

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

Introduction

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

Prototype

@Override
public Class<?> getDeclaringClass() 

Source Link

Document

Returns the Class object representing the class or interface that declares the method represented by this object.

Usage

From source file:com.swingtech.commons.util.ClassUtil.java

public static String getMethodDeclarationString(final Method method) {
    final StringBuffer retStringBuff = new StringBuffer();

    retStringBuff.append(ClassUtil.getClassNameFromFullPath(method.getReturnType()));
    retStringBuff.append(" ");
    retStringBuff.append(ClassUtil.getClassNameFromFullPath(method.getDeclaringClass()));
    retStringBuff.append(".");
    retStringBuff.append(method.getName());
    retStringBuff.append("(");

    if (!Utility.isNullOrEmpty(method.getParameterTypes())) {
        Class c = null;//  www  . jav a  2s .  c om
        for (int index = 0; index < method.getParameterTypes().length; index++) {
            c = method.getParameterTypes()[0];
            if (index > 1) {
                retStringBuff.append(", ");
            }
            retStringBuff.append(ClassUtil.getClassNameFromFullPath(c));
            retStringBuff.append(" arg" + index);
        }
    }

    retStringBuff.append(")");

    return retStringBuff.toString();
}

From source file:org.obiba.opal.rest.client.magma.OpalJavaClient.java

private static Object invokeStaticMethod(Method method, Object... arguments) {
    if (method == null)
        throw new IllegalArgumentException("method cannot be null");

    try {//from  w  w w  . j a v  a2s. c  om
        return method.invoke(null, arguments);
    } catch (RuntimeException | InvocationTargetException | IllegalAccessException e) {
        log.error("Error invoking '{}' method for type {}", method.getName(),
                method.getDeclaringClass().getName(), e);
        throw new RuntimeException("Error invoking '" + method.getName() + "' method for type "
                + method.getDeclaringClass().getName());
    }
}

From source file:kilim.Task.java

private static Method getWovenMethod(Method m) {
    Class<?>[] ptypes = m.getParameterTypes();
    if (!(ptypes.length > 0 && ptypes[ptypes.length - 1].getName().equals("kilim.Fiber"))) {
        // The last param is not "Fiber", so m is not woven.  
        // Get the woven method corresponding to m(..., Fiber)
        boolean found = false;
        LOOP: for (Method wm : m.getDeclaringClass().getDeclaredMethods()) {
            if (wm != m && wm.getName().equals(m.getName())) {
                // names match. Check if the wm has the exact parameter types as m, plus a fiber.
                Class<?>[] wptypes = wm.getParameterTypes();
                if (wptypes.length != ptypes.length + 1
                        || !(wptypes[wptypes.length - 1].getName().equals("kilim.Fiber")))
                    continue LOOP;
                for (int i = 0; i < ptypes.length; i++) {
                    if (ptypes[i] != wptypes[i])
                        continue LOOP;
                }/*w  w w.j  a v a2  s .  com*/
                m = wm;
                found = true;
                break;
            }
        }
        if (!found) {
            throw new IllegalArgumentException(
                    "Found no pausable method corresponding to supplied method: " + m);
        }
    }
    return m;
}

From source file:es.caib.zkib.jxpath.util.ValueUtils.java

/**
 * Return an accessible method (that is, one that can be invoked via
 * reflection) that implements the specified Method.  If no such method
 * can be found, return <code>null</code>.
 *
 * @param method The method that we wish to call
 * @return Method/*w  w w .  j  ava2 s .com*/
 */
public static Method getAccessibleMethod(Method method) {

    // Make sure we have a method to check
    if (method == null) {
        return (null);
    }

    // If the requested method is not public we cannot call it
    if (!Modifier.isPublic(method.getModifiers())) {
        return (null);
    }

    // If the declaring class is public, we are done
    Class clazz = method.getDeclaringClass();
    if (Modifier.isPublic(clazz.getModifiers())) {
        return (method);
    }

    String name = method.getName();
    Class[] parameterTypes = method.getParameterTypes();
    while (clazz != null) {
        // Check the implemented interfaces and subinterfaces
        Method aMethod = getAccessibleMethodFromInterfaceNest(clazz, name, parameterTypes);
        if (aMethod != null) {
            return aMethod;
        }

        clazz = clazz.getSuperclass();
        if (clazz != null && Modifier.isPublic(clazz.getModifiers())) {
            try {
                return clazz.getDeclaredMethod(name, parameterTypes);
            } catch (NoSuchMethodException e) { //NOPMD
                //ignore
            }
        }
    }
    return null;
}

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:com.tmind.framework.pub.utils.MethodUtils.java

private static synchronized Method[] getPublicDeclaredMethods(Class clz) {
    // Looking up Class.getDeclaredMethods is relatively expensive,
    // so we cache the results.
    final Class fclz = clz;
    Method[] result = (Method[]) declaredMethodCache.get(fclz);
    if (result != null) {
        return result;
    }// w ww.  j  a  v  a2  s. co m

    // We have to raise privilege for getDeclaredMethods
    result = (Method[]) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            try {

                return fclz.getDeclaredMethods();

            } catch (SecurityException ex) {
                // this means we're in a limited security environment
                // so let's try going through the public methods
                // and null those those that are not from the declaring
                // class
                Method[] methods = fclz.getMethods();
                for (int i = 0, size = methods.length; i < size; i++) {
                    Method method = methods[i];
                    if (!(fclz.equals(method.getDeclaringClass()))) {
                        methods[i] = null;
                    }
                }
                return methods;
            }
        }
    });

    // Null out any non-public methods.
    for (int i = 0; i < result.length; i++) {
        Method method = result[i];
        if (method != null) {
            int mods = method.getModifiers();
            if (!Modifier.isPublic(mods)) {
                result[i] = null;
            }
        }
    }

    // Add it to the cache.
    declaredMethodCache.put(clz, result);
    return result;
}

From source file:com.facebook.GraphObjectWrapper.java

private static <T extends GraphObject> void verifyCanProxyClass(Class<T> graphObjectClass) {
    if (hasClassBeenVerified(graphObjectClass)) {
        return;/*from  w w  w . j av a2s  . c om*/
    }

    if (!graphObjectClass.isInterface()) {
        throw new FacebookGraphObjectException(
                "GraphObjectWrapper can only wrap interfaces, not class: " + graphObjectClass.getName());
    }

    Method[] methods = graphObjectClass.getMethods();
    for (Method method : methods) {
        String methodName = method.getName();
        int parameterCount = method.getParameterTypes().length;
        Class<?> returnType = method.getReturnType();
        boolean hasPropertyNameOverride = method.isAnnotationPresent(PropertyName.class);

        if (method.getDeclaringClass().isAssignableFrom(GraphObject.class)) {
            // Don't worry about any methods from GraphObject or one of its base classes.
            continue;
        } else if (parameterCount == 1 && returnType == Void.TYPE) {
            if (hasPropertyNameOverride) {
                // If a property override is present, it MUST be valid. We don't fallback
                // to using the method name
                if (!Utility.isNullOrEmpty(method.getAnnotation(PropertyName.class).value())) {
                    continue;
                }
            } else if (methodName.startsWith("set") && methodName.length() > 3) {
                // Looks like a valid setter
                continue;
            }
        } else if (parameterCount == 0 && returnType != Void.TYPE) {
            if (hasPropertyNameOverride) {
                // If a property override is present, it MUST be valid. We don't fallback
                // to using the method name
                if (!Utility.isNullOrEmpty(method.getAnnotation(PropertyName.class).value())) {
                    continue;
                }
            } else if (methodName.startsWith("get") && methodName.length() > 3) {
                // Looks like a valid getter
                continue;
            }
        }

        throw new FacebookGraphObjectException("GraphObjectWrapper can't proxy method: " + method.toString());
    }

    recordClassHasBeenVerified(graphObjectClass);
}

From source file:org.apache.hadoop.ipc.chinamobile.RPC.java

/** Expert: Make multiple, parallel calls to a set of servers. */
public static Object[] call(Method method, Object[][] params, InetSocketAddress[] addrs,
        UserGroupInformation ticket, Configuration conf) throws IOException {

    Invocation[] invocations = new Invocation[params.length];
    for (int i = 0; i < params.length; i++)
        invocations[i] = new Invocation(method, params[i]);
    Client client = CLIENTS.getClient(conf);
    try {/*from w w w .j a  v a  2 s  . c  o m*/
        Writable[] wrappedValues = client.call(invocations, addrs, method.getDeclaringClass(), ticket);

        if (method.getReturnType() == Void.TYPE) {
            return null;
        }

        Object[] values = (Object[]) Array.newInstance(method.getReturnType(), wrappedValues.length);
        for (int i = 0; i < values.length; i++)
            if (wrappedValues[i] != null)
                values[i] = ((ObjectWritable) wrappedValues[i]).get();

        return values;
    } finally {
        CLIENTS.stopClient(client);
    }
}

From source file:org.apache.hadoop.ipc.RPC.java

/** Expert: Make multiple, parallel calls to a set of servers. */
public static Object[] call(Method method, Object[][] params, InetSocketAddress[] addrs,
        UserGroupInformation ticket, Configuration conf) throws IOException, InterruptedException {

    Invocation[] invocations = new Invocation[params.length];
    for (int i = 0; i < params.length; i++)
        invocations[i] = new Invocation(method, params[i]);
    Client client = CLIENTS.getClient(conf);
    try {/* w  ww .  j a v  a  2s  .  c  om*/
        Writable[] wrappedValues = client.call(invocations, addrs, method.getDeclaringClass(), ticket, conf);

        if (method.getReturnType() == Void.TYPE) {
            return null;
        }

        Object[] values = (Object[]) Array.newInstance(method.getReturnType(), wrappedValues.length);
        for (int i = 0; i < values.length; i++)
            if (wrappedValues[i] != null)
                values[i] = ((ObjectWritable) wrappedValues[i]).get();

        return values;
    } finally {
        CLIENTS.stopClient(client);
    }
}

From source file:com.bstek.dorado.data.method.MethodAutoMatchingUtils.java

public static String[] getParameterNames(Method method) throws SecurityException, NoSuchMethodException {
    Class<?> declaringClass = method.getDeclaringClass();
    if (ProxyBeanUtils.isProxy(declaringClass)) {
        Class<?> targetType = ProxyBeanUtils.getProxyTargetType(declaringClass);
        method = targetType.getMethod(method.getName(), method.getParameterTypes());
    }/*from  w w w. j  av a 2  s  . c o m*/
    return paranamer.lookupParameterNames(method);
}