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:de.otto.jsonhome.generator.SpringResourceLinkGenerator.java

@Override
protected String resourcePathFor(final Method method) {
    if (isCandidateForAnalysis(method)) {
        final RequestMapping methodRequestMapping = findAnnotation(method, RequestMapping.class);
        final String resourcePathPrefix = parentResourcePathsFrom(method.getDeclaringClass());
        final String resourcePathSuffix = methodRequestMapping.value().length > 0
                ? methodRequestMapping.value()[0]
                : "";

        return normalized(applicationBaseUri).withPathSegments(resourcePathPrefix, resourcePathSuffix)
                .toString() + queryTemplateFrom(method);
    } else {/*w  w w  .j  av  a  2  s.  co m*/
        return null;
    }
}

From source file:org.nabucco.alfresco.enhScriptEnv.common.script.aop.ScriptableMapListAdapterInterceptor.java

/**
 * {@inheritDoc}// w  ww.java2  s.  c o m
 */
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
    final Object result;
    final Method method = invocation.getMethod();
    final Class<?> declaringClass = method.getDeclaringClass();
    if (Scriptable.class.equals(declaringClass) && invocation instanceof ProxyMethodInvocation) {
        final ProxyMethodInvocation pInvocation = (ProxyMethodInvocation) invocation;
        final Object proxy = pInvocation.getProxy();

        final String methodName = method.getName();
        final Object[] arguments = invocation.getArguments();
        final Class<?>[] parameterTypes = method.getParameterTypes();

        boolean redirect = false;
        String redirectMethod = null;
        Object[] redirectParams = null;
        @SuppressWarnings("rawtypes")
        Class[] redirectParamTypes = null;
        Class<?> redirectDeclaringClass = null;
        Object nonRedirectResult = null;

        // String-switch not supported in Java < 8
        switch (ScriptableMethodName.methodLiteralOf(methodName)) {
        case GET:
            if (proxy instanceof List<?> && int.class.equals(parameterTypes[0])) {
                redirect = true;
                redirectDeclaringClass = List.class;
                redirectMethod = "get";
                redirectParams = new Object[] { arguments[0] };
                redirectParamTypes = new Class[] { parameterTypes[0] };
            } else if (proxy instanceof Map<?, ?>) {
                redirect = true;
                redirectDeclaringClass = Map.class;
                redirectMethod = "get";
                redirectParams = new Object[] { arguments[0] };
                redirectParamTypes = new Class[] { Object.class };
            }
            break;
        case HAS:
            if (proxy instanceof List<?> && int.class.equals(parameterTypes[0])) {
                nonRedirectResult = Boolean
                        .valueOf(((Integer) arguments[0]).intValue() < ((List<?>) proxy).size());
            } else if (proxy instanceof Map<?, ?>) {
                redirect = true;
                redirectDeclaringClass = Map.class;
                redirectMethod = "containsKey";
                redirectParams = new Object[] { arguments[0] };
                redirectParamTypes = new Class[] { Object.class };
            }
            break;
        case PUT:
            if (proxy instanceof List<?> && int.class.equals(parameterTypes[0])) {
                redirect = true;
                redirectDeclaringClass = List.class;
                redirectMethod = ((List<?>) proxy).size() > ((Integer) arguments[0]).intValue() ? "set" : "add";
                redirectParams = new Object[] { arguments[0], arguments[2] };
                redirectParamTypes = new Class[] { int.class, Object.class };
            } else if (proxy instanceof Map<?, ?>) {
                redirect = true;
                redirectDeclaringClass = Map.class;
                redirectMethod = "put";
                redirectParams = new Object[] { arguments[0], arguments[2] };
                redirectParamTypes = new Class[] { Object.class, Object.class };
            }
            break;
        case DELETE:
            if (proxy instanceof List<?> && int.class.equals(parameterTypes[0])) {
                redirect = true;
                redirectDeclaringClass = List.class;
                redirectMethod = "remove";
                redirectParams = arguments;
                redirectParamTypes = parameterTypes;
            } else if (proxy instanceof Map<?, ?>) {
                redirect = true;
                redirectDeclaringClass = Map.class;
                redirectMethod = "remove";
                redirectParams = arguments;
                redirectParamTypes = new Class[] { Object.class };
            }
            break;
        case GETIDS:
            if (proxy instanceof Map<?, ?>) {
                // Note: we do not cover the case of Map + List for getIds, as List is typically only used for indexed access based on
                // known size and not retrieval of keys
                nonRedirectResult = ((Map<?, ?>) proxy).keySet().toArray(new Object[0]);
            } else if (proxy instanceof List<?>) {
                final int size = ((List<?>) proxy).size();
                final Object[] arr = new Object[size];
                for (int idx = 0; idx < size; idx++) {
                    arr[idx] = Integer.valueOf(idx);
                }
            }
            break;
        default:
            // NO-OP
            break;
        }

        final Class<?> returnType = method.getReturnType();
        if (redirect && redirectDeclaringClass != null) {
            final Method redirectMethodHandle = redirectDeclaringClass.getMethod(redirectMethod,
                    redirectParamTypes);
            result = redirectMethodHandle.invoke(proxy, redirectParams);
        } else if (void.class.equals(returnType)) {
            result = null;
        } else if (nonRedirectResult != null && returnType.isInstance(nonRedirectResult)) {
            result = nonRedirectResult;
        } else if (boolean.class.equals(returnType)) {
            result = nonRedirectResult instanceof Boolean ? (Boolean) nonRedirectResult : Boolean.FALSE;
        } else {
            // TODO: what else to do?
            result = null;
        }
    } else {
        result = invocation.proceed();
    }

    return result;
}

From source file:cherry.foundation.testtool.stub.StubServiceImpl.java

@Override
public List<Method> getStubbedMethod(String className) {
    try {//from w  w  w.  j a v  a  2 s .  c  o  m
        if (StringUtils.isEmpty(className)) {
            return repository.getStubbedMethod();
        }
        Class<?> klass = objectMapper.getTypeFactory().constructFromCanonical(className).getRawClass();
        List<Method> list = new ArrayList<>();
        for (Method m : repository.getStubbedMethod()) {
            if (klass == m.getDeclaringClass()) {
                list.add(m);
            }
        }
        return list;
    } catch (IllegalArgumentException ex) {
        return new ArrayList<>();
    }
}

From source file:com.laidians.utils.ClassUtils.java

/**
 * Determine whether the given method is overridable in the given target class.
 * @param method the method to check// w w w  .  j  av a  2s .co  m
 * @param targetClass the target class to check against
 */
private static boolean isOverridable(Method method, Class targetClass) {
    if (Modifier.isPrivate(method.getModifiers())) {
        return false;
    }
    if (Modifier.isPublic(method.getModifiers()) || Modifier.isProtected(method.getModifiers())) {
        return true;
    }
    return getPackageName(method.getDeclaringClass()).equals(getPackageName(targetClass));
}

From source file:org.apache.hadoop.yarn.api.TestPBImplRecords.java

/**
 * this method generate record instance by calling newIntance
 * using reflection, add register the generated value to typeValueCache
 *//*from  w ww . ja va2  s  . c o m*/
@SuppressWarnings("rawtypes")
private static Object generateByNewInstance(Class clazz) throws Exception {
    Object ret = typeValueCache.get(clazz);
    if (ret != null) {
        return ret;
    }
    Method newInstance = null;
    Type[] paramTypes = new Type[0];
    // get newInstance method with most parameters
    for (Method m : clazz.getMethods()) {
        int mod = m.getModifiers();
        if (m.getDeclaringClass().equals(clazz) && Modifier.isPublic(mod) && Modifier.isStatic(mod)
                && m.getName().equals("newInstance")) {
            Type[] pts = m.getGenericParameterTypes();
            if (newInstance == null || (pts.length > paramTypes.length)) {
                newInstance = m;
                paramTypes = pts;
            }
        }
    }
    if (newInstance == null) {
        throw new IllegalArgumentException("type " + clazz.getName() + " does not have newInstance method");
    }
    Object[] args = new Object[paramTypes.length];
    for (int i = 0; i < args.length; i++) {
        args[i] = genTypeValue(paramTypes[i]);
    }
    ret = newInstance.invoke(null, args);
    typeValueCache.put(clazz, ret);
    return ret;
}

From source file:api.wiki.WikiGenerator.java

private Path pageLocation(Method apiMethod) {
    String className = apiMethod.getDeclaringClass().getSimpleName();
    return wikiDirectory().resolve(className);
}

From source file:com.glaf.core.util.ReflectUtils.java

public static boolean isBeanPropertyReadMethod(Method method) {
    return method != null && Modifier.isPublic(method.getModifiers())
            && !Modifier.isStatic(method.getModifiers()) && method.getReturnType() != void.class
            && method.getDeclaringClass() != Object.class && method.getParameterTypes().length == 0
            && ((method.getName().startsWith("get") && method.getName().length() > 3)
                    || (method.getName().startsWith("is") && method.getName().length() > 2));
}

From source file:com.ms.commons.test.annotation.PrepareAnnotationTool.java

public PrepareAnnotationTool(Method method) {
    this.method = method;
    this.prepare = method.getAnnotation(Prepare.class);
    this.noPrepare = method.getAnnotation(NoPrepare.class);
    this.prepareInfo = method.getDeclaringClass().getAnnotation(PrepareInfo.class);
}

From source file:h2o.common.spring.util.ClassUtils.java

/**
 * Determine whether the given method is overridable in the given target class.
 * @param method the method to check/*from  w ww  . j  a  v a  2  s  .  c  o  m*/
 * @param targetClass the target class to check against
 */
@SuppressWarnings("rawtypes")
private static boolean isOverridable(Method method, Class targetClass) {
    if (Modifier.isPrivate(method.getModifiers())) {
        return false;
    }
    if (Modifier.isPublic(method.getModifiers()) || Modifier.isProtected(method.getModifiers())) {
        return true;
    }
    return getPackageName(method.getDeclaringClass()).equals(getPackageName(targetClass));
}

From source file:com.github.reinert.jjschema.v1.CustomSchemaWrapper.java

private HashMap<Method, Field> findProperties() {
    Field[] fields = getJavaType().getDeclaredFields();
    Method[] methods = getJavaType().getMethods();
    // Ordering the properties
    Arrays.sort(methods, new Comparator<Method>() {
        public int compare(Method m1, Method m2) {
            return m1.getName().compareTo(m2.getName());
        }/*from ww  w .j a  va2s . c  o m*/
    });

    LinkedHashMap<Method, Field> props = new LinkedHashMap<Method, Field>();
    // get valid properties (get method and respective field (if exists))
    for (Method method : methods) {
        Class<?> declaringClass = method.getDeclaringClass();
        if (declaringClass.equals(Object.class) || Collection.class.isAssignableFrom(declaringClass)) {
            continue;
        }

        if (isGetter(method)) {
            boolean hasField = false;
            for (Field field : fields) {
                String name = getNameFromGetter(method);
                if (field.getName().equalsIgnoreCase(name)) {
                    props.put(method, field);
                    hasField = true;
                    break;
                }
            }
            if (!hasField) {
                props.put(method, null);
            }
        }
    }
    return props;
}