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:hydrograph.ui.expression.editor.buttons.ValidateExpressionToolButton.java

/**
 * Complies the given expression using engine's jar from ELT-Project's build path. 
 * // w  ww .j  av a2  s .  co m
 * @param expressionStyledText
 * @param fieldMap
 * @param componentName
 * @return DiagnosticCollector 
 *          complete diagnosis of given expression
 * @throws JavaModelException
 * @throws InvocationTargetException
 * @throws ClassNotFoundException
 * @throws MalformedURLException
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 */
@SuppressWarnings({ "unchecked" })
public static DiagnosticCollector<JavaFileObject> compileExpresion(String expressionStyledText,
        Map<String, Class<?>> fieldMap, String componentName)
        throws JavaModelException, InvocationTargetException, ClassNotFoundException, MalformedURLException,
        IllegalAccessException, IllegalArgumentException {
    LOGGER.debug("Compiling expression using Java-Compiler");
    String expressiontext = getExpressionText(expressionStyledText);
    DiagnosticCollector<JavaFileObject> diagnostics = null;
    Object[] returObj = getBuildPathForMethodInvocation();
    List<URL> urlList = (List<URL>) returObj[0];
    String transfromJarPath = (String) returObj[1];
    String propertyFilePath = (String) returObj[2];
    URLClassLoader child = URLClassLoader.newInstance(urlList.toArray(new URL[urlList.size()]));

    Class<?> class1 = Class.forName(HYDROGRAPH_ENGINE_EXPRESSION_VALIDATION_API_CLASS, true, child);
    Thread.currentThread().setContextClassLoader(child);
    Method[] methods = class1.getDeclaredMethods();
    for (Method method : methods) {
        if (method.getParameterTypes().length == 4
                && StringUtils.equals(method.getName(),
                        COMPILE_METHOD_OF_EXPRESSION_JAR_FOR_TRANSFORM_COMPONENTS)
                && !StringUtils.equalsIgnoreCase(componentName, hydrograph.ui.common.util.Constants.FILTER)) {
            method.getDeclaringClass().getClassLoader();
            diagnostics = (DiagnosticCollector<JavaFileObject>) method.invoke(null, expressiontext,
                    propertyFilePath, fieldMap, transfromJarPath);

            break;
        } else if (method.getParameterTypes().length == 4
                && StringUtils.equals(method.getName(), COMPILE_METHOD_OF_EXPRESSION_JAR_FOR_FILTER_COMPONENT)
                && StringUtils.equalsIgnoreCase(componentName, hydrograph.ui.common.util.Constants.FILTER)) {
            method.getDeclaringClass().getClassLoader();
            diagnostics = (DiagnosticCollector<JavaFileObject>) method.invoke(null, expressiontext,
                    propertyFilePath, fieldMap, transfromJarPath);
            break;
        }

    }

    try {
        child.close();
    } catch (IOException ioException) {
        LOGGER.error("Error occurred while closing classloader", ioException);
    }
    return diagnostics;
}

From source file:com.google.code.siren4j.util.ReflectionUtils.java

/**
 * Find the field for the getter method based on the get methods name. It finds the field on the declaring class.
 *
 * @param method cannot be <code>null</code>.
 * @return the field or <code>null</code> if not found.
 *///from   ww w .j a  v a 2s  .  c  o  m
public static Field getGetterField(Method method) {
    if (method == null) {
        throw new IllegalArgumentException("method cannot be null.");
    }
    Class<?> clazz = method.getDeclaringClass();
    String fName = stripGetterPrefix(method.getName());
    Field field = null;
    try {
        field = findField(clazz, fName);
    } catch (Exception ignore) {
    }
    return field;

}

From source file:io.servicecomb.swagger.generator.core.utils.ParamUtils.java

public static void setParameterType(Swagger swagger, Method method, int paramIdx,
        AbstractSerializableParameter<?> parameter) {
    Type paramType = ParamUtils.getGenericParameterType(method, paramIdx);

    ParamUtils.addDefinitions(swagger, paramType);

    Property property = ModelConverters.getInstance().readAsProperty(paramType);

    if (isComplexProperty(property)) {
        // ??????
        String msg = String.format(
                "not allow complex type for %s parameter, method=%s:%s, paramIdx=%d, type=%s",
                parameter.getIn(), method.getDeclaringClass().getName(), method.getName(), paramIdx,
                paramType.getTypeName());
        throw new Error(msg);
    }/*from  w  ww.ja  v a 2  s  .com*/
    parameter.setProperty(property);
}

From source file:com.wavemaker.runtime.server.ServerUtils.java

/**
 * Try to determine parameter names for a given method. This will check {@link ParamName} attributes and debugging
 * symbols; if no name can be found, a default "arg-&lt;position>" name will be used.
 * // w w w  .ja  va 2s.c  o  m
 * This will also continue working of method has been loaded by a non-default classloader.
 * 
 * @param method The method to introspect.
 * @return The names of the parameters in an ordered list.
 */
public static List<String> getParameterNames(Method method) {

    int numParams = method.getParameterTypes().length;
    List<String> ret = new ArrayList<String>(numParams);
    Annotation[][] paramAnnotations = method.getParameterAnnotations();
    Class<?> paramNameClass = ClassLoaderUtils.loadClass(ParamName.class.getName(),
            method.getDeclaringClass().getClassLoader());

    String[] methodParameterNames;

    try {
        AdaptiveParanamer ap = new AdaptiveParanamer();
        methodParameterNames = ap.lookupParameterNames(method);
        ap = null;
    } catch (ParameterNamesNotFoundException e) {
        logger.info("No parameter names found for method " + method.getName());
        methodParameterNames = new String[numParams];
    }

    for (int i = 0; i < numParams; i++) {
        String paramName = null;

        if (paramName == null) {
            for (Annotation ann : paramAnnotations[i]) {
                if (paramNameClass.isAssignableFrom(ann.annotationType())) {
                    try {
                        Method nameMethod = paramNameClass.getMethod("name");
                        paramName = (String) nameMethod.invoke(ann);
                    } catch (SecurityException e) {
                        throw new WMRuntimeException(e);
                    } catch (NoSuchMethodException e) {
                        throw new WMRuntimeException(e);
                    } catch (IllegalAccessException e) {
                        throw new WMRuntimeException(e);
                    } catch (InvocationTargetException e) {
                        throw new WMRuntimeException(e);
                    }

                    break;
                }
            }
        }

        if (paramName == null && methodParameterNames != null) {
            paramName = methodParameterNames[i];
        }

        if (paramName == null) {
            logger.warn("no parameter name information for parameter " + i + ", method: " + method.getName());
            paramName = "arg-" + (i + 1);
        }

        ret.add(paramName);
    }

    return ret;
}

From source file:org.agiso.core.i18n.util.I18nUtils.java

public static String getCode(Method m) {
    if (m.isAnnotationPresent(I18n.class)) {
        if (m.getAnnotation(I18n.class).value().length() > 0) {
            return m.getAnnotation(I18n.class).value();
        } else {//w ww .  jav  a2 s  . c o  m
            return m.getDeclaringClass().getCanonicalName() + CODE_SEPARATOR + findGetterFieldName(m);
        }
    }
    // else if(m.isAnnotationPresent(I18nRef.class)) {
    //    Object ref = m.getAnnotation(I18nRef.class).value();
    //    if(((Class<?>)ref).isEnum()) {
    //       return getCode((Enum<?>)ref);
    //    } else {
    //       return getCode((Class<?>)ref);
    //    }
    // }
    return m.getDeclaringClass().getCanonicalName() + CODE_SEPARATOR + findGetterFieldName(m);
}

From source file:com.sf.ddao.crud.param.CRUDParameterService.java

public static Class<?> getCRUDDaoBean(Context ctx, int idx) {
    final MethodCallCtx callCtx = CtxHelper.get(ctx, MethodCallCtx.class);
    final Method method = callCtx.getMethod();
    if (idx != USE_GENERICS) {
        Type beanClass;/* www . j a v  a 2  s . c o m*/
        if (idx == DefaultParameter.RETURN_ARG_IDX) {
            beanClass = method.getGenericReturnType();
        } else {
            beanClass = method.getGenericParameterTypes()[idx];
        }
        if (beanClass instanceof Class) {
            return (Class) beanClass;
        }
    }
    Class<?> iFace = callCtx.getSubjClass();
    for (Type type : iFace.getGenericInterfaces()) {
        final ParameterizedType parameterizedType = (ParameterizedType) type;
        if (parameterizedType.getRawType().equals(method.getDeclaringClass())) {
            final Type[] typeArguments = parameterizedType.getActualTypeArguments();
            return (Class<?>) typeArguments[GENERICS_ARG_NUM];
        }
    }
    throw new RuntimeException(iFace + " expected to extend " + CRUDDao.class);
}

From source file:org.apache.servicecomb.swagger.generator.core.utils.ParamUtils.java

public static void setParameterType(Swagger swagger, Method method, int paramIdx,
        AbstractSerializableParameter<?> parameter) {
    Type paramType = ParamUtils.getGenericParameterType(method, paramIdx);

    ParamUtils.addDefinitions(swagger, paramType);

    Property property = ModelConverters.getInstance().readAsProperty(paramType);

    if (isComplexProperty(property)) {
        // cannot set a simple parameter(header, query, etc.) as complex type
        String msg = String.format(
                "not allow complex type for %s parameter, method=%s:%s, paramIdx=%d, type=%s",
                parameter.getIn(), method.getDeclaringClass().getName(), method.getName(), paramIdx,
                paramType.getTypeName());
        throw new Error(msg);
    }//from  ww w  . j  a v a 2  s .  c om
    parameter.setProperty(property);
}

From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.java

/**
 * Make the given method accessible, explicitly setting it accessible if
 * necessary. The {@code setAccessible(true)} method is only called
 * when actually necessary, to avoid unnecessary conflicts with a JVM
 * SecurityManager (if active).//  ww w  .  j a  v a2 s  .c  om
 * @param method the method to make accessible
 * @see java.lang.reflect.Method#setAccessible
 */
public static void makeAccessible(Method method) {
    if ((!Modifier.isPublic(method.getModifiers())
            || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible()) {
        method.setAccessible(true);
    }
}

From source file:com.cloudera.api.model.ApiModelTest.java

private static String getMethodName(Method m) {
    return String.format("%s::%s()", m.getDeclaringClass().getName(), m.getName());
}

From source file:com.taobao.weex.wson.Wson.java

private static final List<Method> getBeanMethod(String key, Class targetClass) {
    List<Method> methods = methodsCache.get(key);
    if (methods == null) {
        methods = new ArrayList<>();
        Method[] allMethods = targetClass.getMethods();
        for (Method method : allMethods) {
            if (method.getDeclaringClass() == Object.class) {
                continue;
            }/*from w w  w  . j av a 2s.  com*/
            if ((method.getModifiers() & Modifier.STATIC) != 0) {
                continue;
            }
            String methodName = method.getName();
            if (methodName.startsWith(METHOD_PREFIX_GET) || methodName.startsWith(METHOD_PREFIX_IS)) {
                if (method.getAnnotation(JSONField.class) != null) {
                    throw new UnsupportedOperationException(
                            "getBeanMethod JSONField Annotation Not Handled, Use toJSON");
                }
                methods.add(method);
            }
        }
        methodsCache.put(key, methods);
    }
    return methods;
}