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.alibaba.dragoon.patrol.spring.DragoonMethodInterceptor.java

public MethodInfo getMethodInfo(MethodInvocation invocation, String paramter) {
    Object thisObject = invocation.getThis();
    Method method = invocation.getMethod();

    Class<?> clazz = null;//from  www  .  java2 s  .c  om

    try {
        if (thisObject == null) {
            clazz = method.getDeclaringClass();
        } else {
            // ?10?
            for (int i = 0; i < 10; ++i) {
                if (thisObject instanceof org.springframework.aop.framework.Advised) {
                    TargetSource targetSource = ((org.springframework.aop.framework.Advised) thisObject)
                            .getTargetSource();

                    if (targetSource == null) {
                        break;
                    }

                    Object target = targetSource.getTarget();
                    if (target != null) {
                        thisObject = target;
                    } else {
                        clazz = targetSource.getTargetClass();
                        break;
                    }
                } else {
                    break;
                }
            }

            if (clazz == null) {
                clazz = thisObject.getClass();

                if (clazz.getName().startsWith("$")) {
                    clazz = method.getDeclaringClass();
                }
            }
        }
    } catch (Exception ex) {
        LOG.error(ex.getMessage(), ex);
    }

    if (clazz == null) {
        clazz = method.getDeclaringClass();
    }

    return new MethodInfo(clazz, method, paramter);
}

From source file:de.xaniox.heavyspleef.commands.base.CommandManagerService.java

private void unregisterRecursively(Class<?> clazz, Iterator<CommandContainer> iterator) {
    while (iterator.hasNext()) {
        CommandContainer container = iterator.next();
        Method method = container.getCommandMethod();
        Set<CommandContainer> childs = container.getChildCommands();

        if (method.getDeclaringClass() == clazz) {
            iterator.remove();/* w  w w.  j a  va  2  s  . c o m*/
        } else if (childs != null && !childs.isEmpty()) {
            unregisterRecursively(clazz, childs.iterator());
        }
    }
}

From source file:com.bstek.dorado.config.ExpressionMethodInterceptor.java

protected void discoverInterceptingMethods(Class<?> clazz) throws Exception {
    interceptingReadMethods = new HashMap<Method, ReadMethodDescriptor>();
    interceptingWriteMethods = new HashMap<Method, Method>();
    Map<Method, ReadMethodDescriptor> getterMethods = interceptingReadMethods;
    Map<Method, Method> setterMethods = interceptingWriteMethods;
    Map<String, Expression> expressionProperties = getExpressionProperties();

    BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        String property = propertyDescriptor.getName();
        if (expressionProperties.containsKey(property)) {
            Method readMethod = propertyDescriptor.getReadMethod();
            Method writeMethod = propertyDescriptor.getWriteMethod();

            if (readMethod != null) {
                if (readMethod.getDeclaringClass() != clazz) {
                    readMethod = clazz.getMethod(readMethod.getName(), readMethod.getParameterTypes());
                }//from w  w  w  .  java2  s  . c om
                getterMethods.put(readMethod, new ReadMethodDescriptor(property, null));
            }
            if (writeMethod != null) {
                if (writeMethod.getDeclaringClass() != clazz) {
                    writeMethod = clazz.getMethod(writeMethod.getName(), writeMethod.getParameterTypes());
                }
                setterMethods.put(writeMethod, readMethod);
            }
        }
    }
}

From source file:com.taobao.adfs.util.Utilities.java

public static String deepToString(Object object) {
    if (object == null) {
        return "null";
    } else if (object instanceof Throwable) {
        return getThrowableStackTrace((Throwable) object);
    } else if (object.getClass().isEnum()) {
        return object.toString();
    } else if (object.getClass().isArray()) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(object.getClass().getSimpleName());
        int length = Array.getLength(object);
        stringBuilder.insert(stringBuilder.length() - 1, Array.getLength(object)).append("{");
        for (int i = 0; i < length; i++) {
            stringBuilder.append(deepToString(Array.get(object, i)));
            if (i < length - 1)
                stringBuilder.append(',');
        }//from ww w  . ja  v  a  2 s  . c  o  m
        return stringBuilder.append("}").toString();
    } else if (List.class.isAssignableFrom(object.getClass())) {
        List<?> listObject = ((List<?>) object);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(object.getClass().getSimpleName()).append('[').append(listObject.size())
                .append(']');
        stringBuilder.append("{");
        for (Object subObject : listObject) {
            stringBuilder.append(deepToString(subObject)).append(',');
        }
        if (!listObject.isEmpty())
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        return stringBuilder.append('}').toString();
    } else {
        try {
            Method toStringMethod = Invocation.getPublicMethod(object.getClass(), "toString");
            if (toStringMethod.getDeclaringClass() == Object.class)
                return toStringByFields(object, false);
        } catch (Throwable t) {
        }
        try {
            return object.toString();
        } catch (Throwable t) {
            return "FailToString";
        }
    }
}

From source file:org.ff4j.aop.FeatureAdvisor.java

/**
 * Store single instance of loggers but init if does not exist
 * /* w  ww . j  a v a 2 s  .co  m*/
 * @param targetMethod
 *            current processed method
 * @return singleton for class related to this execution
 */
private Logger getLogger(Method targetMethod) {
    String methodName = targetMethod.getDeclaringClass().getCanonicalName();
    // Register logger if require
    if (!targetLoggers.containsKey(methodName)) {
        targetLoggers.put(methodName, LoggerFactory.getLogger(targetMethod.getDeclaringClass()));
    }
    return targetLoggers.get(methodName);
}

From source file:com.teletalk.jserver.util.aop.MethodInvocationDebugLogger.java

/**
 *///w  ww.j a  v a2 s  .c o  m
public Object invoke(final MethodInvocation methodInvocation) throws Throwable {
    Method method = methodInvocation.getMethod();
    String paramLogString = null;
    long executionStartTime = System.currentTimeMillis();
    Log logger = this.logger;
    String methodName;
    if (logger == null) {
        logger = LogFactory.getLog(method.getDeclaringClass());
        methodName = method.getName();
    } else
        methodName = method.getDeclaringClass().getName() + "." + method.getName();

    if (logger.isDebugEnabled()) {
        paramLogString = "";
        Object[] arguments = methodInvocation.getArguments();
        if (arguments != null) {
            for (int i = 0; i < arguments.length; i++) {
                paramLogString += StringUtils.limitStringLength(StringUtils.toString(arguments[i]),
                        this.maxParameterStringRepresentationLength);
                if (i < (arguments.length - 1))
                    paramLogString += ", ";
            }
        }

        logger.debug("Executing " + methodName + "(" + paramLogString + ").");
    }

    Object returnValue = methodInvocation.proceed();

    if (logger.isDebugEnabled()) {
        if ((method.getReturnType() == null) || method.getReturnType().equals(Void.TYPE)) {
            logger.debug("Done executing " + methodName + "(" + paramLogString + ") after "
                    + (System.currentTimeMillis() - executionStartTime) + "ms.");
        } else {
            logger.debug("Done executing " + methodName + "(" + paramLogString + ") after "
                    + (System.currentTimeMillis() - executionStartTime) + "ms" + " - return value: "
                    + StringUtils.limitStringLength(StringUtils.toString(returnValue),
                            this.maxReturnValueStringRepresentationLength)
                    + ".");
        }
    }

    return returnValue;
}

From source file:at.ac.tuwien.infosys.jcloudscale.test.unit.TestReflectionUtil.java

@Test
public void testOverride() throws Exception {
    SubType obj = new SubType();

    // resolveMethod() cannot be used because ReflectionUtils.findMethod() would just find overridden(Serializable)
    Method method = findMethod(obj.getClass(), "overridden", String.class);
    assertNotNull(method);//w  w w  .j  a v  a2  s  .  c  o m
    assertSame(SubType.class, method.getDeclaringClass());

    method = resolveMethod(obj.getClass(), "overridden", Serializable.class);
    assertNotNull(method);
    assertSame(SubType.class, method.getDeclaringClass());
}

From source file:model.job.metadata.ResourceMetadata.java

/**
 * Merges the properties of another ResourceMetadata into this one.
 * /*from  w  ww.  j a  va 2  s .c o m*/
 * <p>
 * If the other ResourceMetadata specifies properties, then those properties
 * take precedence. If the other ResourceMetadata contains a null value for
 * a property that exists in this object, then this object's property is
 * unchanged unless the overwriteNull flag is set to true.
 * </p>
 * 
 * @param other
 *            The ResourceMetadata properties to merge
 * @param overwriteNull
 *            True if null values in the other ResourceMetadata should
 *            overwrite values in this object. False if not.
 * @throws InvalidInputException 
 */
public void merge(ResourceMetadata other, boolean overwriteNull) throws InvalidInputException {
    final List<String> protectedNames = Arrays.asList("setCreatedBy", "setCreatedOn", "setCreatedByJobId");

    for (Method fromMethod : this.getClass().getMethods()) {
        if (fromMethod.getDeclaringClass().equals(this.getClass()) && fromMethod.getName().startsWith("get")) {
            mergeMethod(other, overwriteNull, fromMethod, protectedNames);
        }
    }
}

From source file:at.ac.tuwien.infosys.jcloudscale.test.unit.TestReflectionUtil.java

@Test
public void testCovariance() throws Exception {
    SubType obj = new SubType();

    Method method = resolveMethod(obj.getClass(), "covariant", String.class);
    assertNotNull(method);//  w w w  . j  ava  2  s .  com
    assertSame(SuperType.class, method.getDeclaringClass());

    method = resolveMethod(obj.getClass(), "covariant", Object.class);
    assertNotNull(method);
    assertSame(SubType.class, method.getDeclaringClass());
}

From source file:at.ac.tuwien.infosys.jcloudscale.test.unit.TestReflectionUtil.java

@Test
public void testContravariance() throws Exception {
    SubType obj = new SubType();

    Method method = resolveMethod(obj.getClass(), "contravariant", Integer.class);
    assertNotNull(method);/*from w w  w.  j  a v a 2s  .  c  o m*/
    assertSame(SubType.class, method.getDeclaringClass());

    method = resolveMethod(obj.getClass(), "contravariant", Number.class);
    assertNotNull(method);
    assertSame(SuperType.class, method.getDeclaringClass());
}