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.datatorrent.stram.webapp.OperatorDiscoverer.java

private JSONArray getClassProperties(Class<?> clazz, int level) throws IntrospectionException {
    JSONArray arr = new JSONArray();
    TypeDiscoverer td = new TypeDiscoverer();
    try {/*from   w  w w .  j  ava2  s  . c o m*/
        for (PropertyDescriptor pd : Introspector.getBeanInfo(clazz).getPropertyDescriptors()) {
            Method readMethod = pd.getReadMethod();
            if (readMethod != null) {
                if (readMethod.getDeclaringClass() == java.lang.Enum.class) {
                    // skip getDeclaringClass
                    continue;
                } else if ("class".equals(pd.getName())) {
                    // skip getClass
                    continue;
                }
            } else {
                // yields com.datatorrent.api.Context on JDK6 and com.datatorrent.api.Context.OperatorContext with JDK7
                if ("up".equals(pd.getName())
                        && com.datatorrent.api.Context.class.isAssignableFrom(pd.getPropertyType())) {
                    continue;
                }
            }
            //LOG.info("name: " + pd.getName() + " type: " + pd.getPropertyType());

            Class<?> propertyType = pd.getPropertyType();
            if (propertyType != null) {
                JSONObject propertyObj = new JSONObject();
                propertyObj.put("name", pd.getName());
                propertyObj.put("canGet", readMethod != null);
                propertyObj.put("canSet", pd.getWriteMethod() != null);
                if (readMethod != null) {
                    for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
                        OperatorClassInfo oci = classInfo.get(c.getName());
                        if (oci != null) {
                            MethodInfo getMethodInfo = oci.getMethods.get(readMethod.getName());
                            if (getMethodInfo != null) {
                                addTagsToProperties(getMethodInfo, propertyObj);
                                break;
                            }
                        }
                    }
                    // type can be a type symbol or parameterized type
                    td.setTypeArguments(clazz, readMethod.getGenericReturnType(), propertyObj);
                } else {
                    if (pd.getWriteMethod() != null) {
                        td.setTypeArguments(clazz, pd.getWriteMethod().getGenericParameterTypes()[0],
                                propertyObj);
                    }
                }
                //if (!propertyType.isPrimitive() && !propertyType.isEnum() && !propertyType.isArray() && !propertyType.getName().startsWith("java.lang") && level < MAX_PROPERTY_LEVELS) {
                //  propertyObj.put("properties", getClassProperties(propertyType, level + 1));
                //}
                arr.put(propertyObj);
            }
        }
    } catch (JSONException ex) {
        throw new RuntimeException(ex);
    }
    return arr;
}

From source file:freemarker.ext.dump.BaseDumpDirective.java

private Map<String, Object> getObjectDump(TemplateHashModelEx model, Object object)
        throws TemplateModelException {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put(Key.TYPE.toString(), object.getClass().getName());

    if (object instanceof java.lang.reflect.Method)
        return map;

    // Compile the collections of properties and methods available to the template
    SortedMap<String, Object> properties = new TreeMap<String, Object>();
    SortedMap<String, Object> methods = new TreeMap<String, Object>();

    // keys() gets only values visible to template based on the BeansWrapper used.
    // Note: if the BeansWrapper exposure level > BeansWrapper.EXPOSE_PROPERTIES_ONLY,
    // keys() returns both method and property name for any available method with no
    // parameters: e.g., both name and getName(). We are going to eliminate the latter.
    TemplateCollectionModel keys = model.keys();
    TemplateModelIterator iModel = keys.iterator();

    // Create a Set from keys so we can use the Set API.
    Set<String> keySet = new HashSet<String>();
    while (iModel.hasNext()) {
        String key = iModel.next().toString();
        keySet.add(key);//from  w  w w  . j ava 2  s. c  o m
    }

    if (keySet.size() > 0) {

        Class<?> cls = object.getClass();
        Method[] classMethods = cls.getMethods();

        // Iterate through the methods rather than the keys, so that we can remove
        // some keys based on reflection on the methods. We also want to remove duplicates
        // like name/getName - we'll keep only the first form.
        for (Method method : classMethods) {

            if ("declaringClass".equals(method.getName()))
                continue;

            // Eliminate methods declared on Object
            // and other unusual places that can cause problems.
            Class<?> c = method.getDeclaringClass();

            if (c == null || c.equals(java.lang.Object.class) || c.equals(java.lang.reflect.Constructor.class)
                    || c.equals(java.lang.reflect.Field.class))
                continue;
            if (c.getPackage().getName().startsWith("sun.") || c.getPackage().getName().startsWith("java.lang")
                    || c.getPackage().getName().startsWith("java.security"))
                continue;

            // Eliminate deprecated methods
            if (method.isAnnotationPresent(Deprecated.class)) {
                continue;
            }

            // Include only methods included in keys(). This factors in visibility
            // defined by the model's BeansWrapper.                 
            String methodName = method.getName();

            Matcher matcher = PROPERTY_NAME_PATTERN.matcher(methodName);
            // If the method name starts with "get" or "is", check if it's available
            // as a property
            if (matcher.find()) {
                String propertyName = getPropertyName(methodName);

                // The method is available as a property
                if (keySet.contains(propertyName)) {
                    try {
                        TemplateModel value = model.get(propertyName);
                        properties.put(propertyName, getDump(value));
                    } catch (Throwable th) {
                        log.error("problem dumping " + propertyName + " on " + object.getClass().getName()
                                + " declared in " + c.getName(), th);
                    }
                    continue;
                }
            }

            // Else look for the entire methodName in the key set, to include
            // those that are exposed as methods rather than properties. 
            if (keySet.contains(methodName)) {
                String methodDisplayName = getMethodDisplayName(method);
                // If no arguments, invoke the method to get the result
                if (methodDisplayName.endsWith("()")) {
                    SimpleMethodModel methodModel = (SimpleMethodModel) model.get(methodName);
                    try {
                        Object result = methodModel.exec(null);
                        ObjectWrapper wrapper = getWrapper(model);
                        TemplateModel wrappedResult = wrapper.wrap(result);
                        methods.put(methodDisplayName, getDump(wrappedResult));
                    } catch (Exception e) {
                        log.error(e, e);
                    }
                    // Else display method name, parameter types, and return type
                } else {
                    String returnTypeName = getReturnTypeName(method);
                    Map<String, String> methodValue = new HashMap<String, String>();
                    if (!returnTypeName.equals("void")) {
                        methodValue.put(Key.TYPE.toString(), returnTypeName);
                    }
                    methods.put(methodDisplayName, methodValue);
                }
            }
        }
    }

    Map<String, Object> objectValue = new HashMap<String, Object>(2);
    objectValue.put(Key.PROPERTIES.toString(), properties);
    objectValue.put(Key.METHODS.toString(), methods);

    map.put(Key.VALUE.toString(), objectValue);
    return map;
}

From source file:nl.strohalm.cyclos.utils.logging.LoggingHandler.java

/**
 * Builds an action string for the method execution. Will be something like userName.methodName if not detailed, or userName.methodName([param1,
 * param2, ...]) if detailed/*from www  .  j a  va2s.  co m*/
 */
private String buildActionString(final User user, final Permission permission, final Method method,
        final Object[] args, final Object retVal, final boolean useReturn) {
    final StringBuilder sb = new StringBuilder();
    final String className = StringUtils.replace(ClassHelper.getClassName(method.getDeclaringClass()), "Impl",
            "");
    final String methodName = method.getName();
    sb.append(user.getUsername()).append(" - ").append(className).append('.').append(methodName);
    if (permission != null) {
        sb.append('[').append(permission.module()).append('.').append(permission.operation()).append(']');
    }
    final boolean detailed = getTraceLogger().isLoggable(TraceLevel.DETAILED.getLevel());
    if (detailed) {
        // Don't log the parameters of some methods
        final boolean logParameters = logParameters(methodName);
        if (logParameters && useReturn) {
            sb.append(", Returning ").append(FormatObject.formatArgument(retVal)).append(", Arguments ");
        }
        // Append the arguments
        sb.append('(');
        for (int i = 0; i < args.length; i++) {
            if (i > 0) {
                sb.append(", ");
            }
            if (logParameters) {
                final Object argument = args[i];
                if (!fetchService.isInitialized(argument)) {
                    sb.append(FormatObject.formatArgument(argument));
                } else {
                    sb.append(FormatObject.formatVO(argument));
                }
            } else {
                sb.append("***");
            }
        }
        sb.append(')');
    }
    return sb.toString();
}

From source file:org.grails.datastore.mapping.query.order.ManualEntityOrdering.java

public List applyOrder(List results, Query.Order order) {
    final String name = order.getProperty();

    @SuppressWarnings("hiding")
    final PersistentEntity entity = getEntity();
    PersistentProperty property = entity.getPropertyByName(name);
    if (property == null) {
        final PersistentProperty identity = entity.getIdentity();
        if (name.equals(identity.getName())) {
            property = identity;/*  w  ww.j  ava  2 s.  com*/
        }
    }

    if (property != null) {
        final PersistentProperty finalProperty = property;
        Collections.sort(results, new Comparator() {

            public int compare(Object o1, Object o2) {

                if (entity.isInstance(o1) && entity.isInstance(o2)) {
                    final String propertyName = finalProperty.getName();
                    Method readMethod = cachedReadMethods.get(propertyName);
                    if (readMethod == null) {
                        BeanWrapper b = PropertyAccessorFactory.forBeanPropertyAccess(o1);
                        final PropertyDescriptor pd = b.getPropertyDescriptor(propertyName);
                        if (pd != null) {
                            readMethod = pd.getReadMethod();
                            if (readMethod != null) {
                                ReflectionUtils.makeAccessible(readMethod);
                                cachedReadMethods.put(propertyName, readMethod);
                            }
                        }
                    }

                    if (readMethod != null) {
                        final Class<?> declaringClass = readMethod.getDeclaringClass();
                        if (declaringClass.isInstance(o1) && declaringClass.isInstance(o2)) {
                            Object left = ReflectionUtils.invokeMethod(readMethod, o1);
                            Object right = ReflectionUtils.invokeMethod(readMethod, o2);

                            if (left == null && right == null)
                                return 0;
                            if (left != null && right == null)
                                return 1;
                            if (left == null)
                                return -1;
                            if ((left instanceof Comparable) && (right instanceof Comparable)) {
                                return ((Comparable) left).compareTo(right);
                            }
                        }
                    }
                }
                return 0;
            }
        });
    }

    if (order.getDirection() == Query.Order.Direction.DESC) {
        results = reverse(results);
    }

    return results;
}

From source file:plugins.PlayReader.java

public Operation parseMethod(Method method) {
    return parseMethod(method.getDeclaringClass(), method, Collections.<Parameter>emptyList());
}

From source file:com.liferay.portal.jsonwebservice.JSONWebServiceConfigurator.java

private void _registerJSONWebServiceAction(Class<?> implementationClass, Method method) throws Exception {

    String path = _jsonWebServiceMappingResolver.resolvePath(implementationClass, method);

    String httpMethod = _jsonWebServiceMappingResolver.resolveHttpMethod(method);

    if (_invalidHttpMethods.contains(httpMethod)) {
        return;//w ww.j a v a  2  s .  c  o  m
    }

    Class<?> utilClass = _loadUtilClass(implementationClass);

    try {
        method = utilClass.getMethod(method.getName(), method.getParameterTypes());
    } catch (NoSuchMethodException nsme) {
        return;
    }

    JSONWebServiceActionsManagerUtil.registerJSONWebServiceAction(_servletContextPath,
            method.getDeclaringClass(), method, path, httpMethod);

    _registeredActionsCount++;
}

From source file:com.impetus.kundera.proxy.cglib.CglibLazyInitializer.java

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (constructed) {

        String methodName = method.getName();
        int params = args.length;

        if (params == 0) {

            if (isUninitialized() && method.equals(getIdentifierMethod)) {
                return getIdentifier();
            }//w  ww.j a va2  s. c o m

            else if ("getKunderaLazyInitializer".equals(methodName)) {
                return this;
            }

        }

        Object target = getImplementation();
        try {
            final Object returnValue;
            if (method.isAccessible()) {
                if (!method.getDeclaringClass().isInstance(target)) {
                    throw new ClassCastException(target.getClass().getName());
                }
                returnValue = method.invoke(target, args);
            } else {
                if (!method.isAccessible()) {
                    method.setAccessible(true);
                }
                returnValue = method.invoke(target, args);
            }
            return returnValue == target ? proxy : returnValue;
        } catch (InvocationTargetException ite) {
            throw ite.getTargetException();
        }
    } else {
        // while constructor is running
        throw new LazyInitializationException("unexpected case hit, method=" + method.getName());
    }

}

From source file:com.autentia.wuija.persistence.event.AnnotationEventListener.java

private Object invokeAnnotatedMethod(Session session, Object entity, Class<? extends Annotation> annotation) {
    final Method annotatedMethod = ClassUtils.findAnnotatedMethod(entity.getClass(), annotation);
    if (annotatedMethod == null) {
        return null;
    }/*  w ww  .  j a va2 s. co  m*/

    if (log.isDebugEnabled()) {
        log.debug(
                "Invoking " + annotation.getSimpleName() + " method, for class " + entity.getClass().getName());
    }

    final boolean accesible = annotatedMethod.isAccessible();
    annotatedMethod.setAccessible(true); // Se hace el mtodo accesible, por si es privado
    try {
        if (annotatedMethod.getParameterTypes().length == 1) {
            return annotatedMethod.invoke(entity, session);
        }
        return annotatedMethod.invoke(entity);

    } catch (IllegalArgumentException e) {
        final String msg = "Cannot invoke event listener method. Method for class "
                + annotatedMethod.getDeclaringClass().getName() + "." + annotatedMethod.getName()
                + " should have no parameters, or just one parameter, the Hibernate session.";
        log.fatal(msg, e);
        throw new IllegalArgumentException(msg, e);

    } catch (IllegalAccessException e) {
        final String msg = "Cannot invoke event listener. Method for class "
                + annotatedMethod.getDeclaringClass().getName() + "." + annotatedMethod.getName()
                + " is not accesible.";
        log.fatal(msg, e);
        throw new IllegalArgumentException(msg, e);

    } catch (InvocationTargetException e) {
        final String msg = "Cannot invoke event listener. Method for class "
                + annotatedMethod.getDeclaringClass().getName() + "." + annotatedMethod.getName()
                + " is not accesible.";
        log.fatal(msg, e);
        throw new IllegalArgumentException(msg, e);

    } finally {
        annotatedMethod.setAccessible(accesible); // Se restaura la accesibilidad del metodo
    }
}

From source file:ca.uhn.fhir.rest.method.ReadMethodBinding.java

@SuppressWarnings("unchecked")
public ReadMethodBinding(Class<? extends IBaseResource> theAnnotatedResourceType, Method theMethod,
        FhirContext theContext, Object theProvider) {
    super(theAnnotatedResourceType, theMethod, theContext, theProvider);

    Validate.notNull(theMethod, "Method must not be null");

    Integer idIndex = MethodUtil.findIdParameterIndex(theMethod, getContext());
    Integer versionIdIndex = MethodUtil.findVersionIdParameterIndex(theMethod);

    Class<?>[] parameterTypes = theMethod.getParameterTypes();

    mySupportsVersion = theMethod.getAnnotation(Read.class).version();
    myIdIndex = idIndex;//  w ww .  j  av a 2s.  c o  m
    myVersionIdIndex = versionIdIndex;

    if (myIdIndex == null) {
        throw new ConfigurationException("@" + Read.class.getSimpleName() + " method " + theMethod.getName()
                + " on type \"" + theMethod.getDeclaringClass().getName()
                + "\" does not have a parameter annotated with @" + IdParam.class.getSimpleName());
    }
    myIdParameterType = (Class<? extends IIdType>) parameterTypes[myIdIndex];

    if (!IIdType.class.isAssignableFrom(myIdParameterType)) {
        throw new ConfigurationException(
                "ID parameter must be of type IdDt or IdType - Found: " + myIdParameterType);
    }
    if (myVersionIdIndex != null && !IdDt.class.equals(parameterTypes[myVersionIdIndex])) {
        throw new ConfigurationException("Version ID parameter must be of type: "
                + IdDt.class.getCanonicalName() + " - Found: " + parameterTypes[myVersionIdIndex]);
    }

}

From source file:com.izforge.izpack.util.SelfModifier.java

/**
 * Check the method for the required properties (public, static, params:(String[])).
 *
 * @param method the method/*from ww  w  .j a  v  a 2s .co m*/
 * @throws NullPointerException     if <code>method</code> is null
 * @throws IllegalArgumentException if <code>method</code> is not public, static, and take a
 *                                  String array as it's only argument, or of it's declaring class is not public.
 * @throws SecurityException        if access to the method is denied
 */
private void initMethod(Method method) {
    int mod = method.getModifiers();
    if ((mod & Modifier.PUBLIC) == 0 || (mod & Modifier.STATIC) == 0) {
        throw new IllegalArgumentException("Method not public and static");
    }

    Class[] params = method.getParameterTypes();
    if (params.length != 1 || !params[0].isArray()
            || !"java.lang.String".equals(params[0].getComponentType().getName())) {
        throw new IllegalArgumentException("Method must accept String array");
    }

    Class clazz = method.getDeclaringClass();
    mod = clazz.getModifiers();
    if ((mod & Modifier.PUBLIC) == 0 || (mod & Modifier.INTERFACE) != 0) {
        throw new IllegalArgumentException("Method must be in a public class");
    }

    this.method = method;
}