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:guru.qas.martini.runtime.harness.MartiniCallable.java

protected Object getBean(Method method) {
    Class<?> declaringClass = method.getDeclaringClass();
    return beanFactory.getBean(declaringClass);
}

From source file:hu.bme.mit.sette.tools.spf.SpfGenerator.java

private void createGeneratedFiles() throws IOException {
    // generate main() for each snippet
    for (SnippetContainer container : getSnippetProject().getModel().getContainers()) {
        // skip container with higher java version than supported
        if (container.getRequiredJavaVersion().compareTo(getTool().getSupportedJavaVersion()) > 0) {
            // TODO error handling
            System.err.println("Skipping container: " + container.getJavaClass().getName()
                    + " (required Java version: " + container.getRequiredJavaVersion() + ")");
            continue;
        }//  w ww  . j ava 2 s.  c o  m

        for (Snippet snippet : container.getSnippets().values()) {
            Method method = snippet.getMethod();
            Class<?> javaClass = method.getDeclaringClass();
            Class<?>[] parameterTypes = method.getParameterTypes();

            // create .jpf descriptor
            JPFConfig jpfConfig = new JPFConfig();
            jpfConfig.target = javaClass.getName() + '_' + method.getName();

            String symbMethod = javaClass.getName() + '.' + method.getName() + '('
                    + StringUtils.repeat("sym", "#", parameterTypes.length) + ')';

            jpfConfig.symbolicMethod.add(symbMethod);

            jpfConfig.classpath = "build/";

            for (File libraryFile : getSnippetProject().getFiles().getLibraryFiles()) {
                jpfConfig.classpath += ',' + getSnippetProjectSettings().getLibraryDirectoryPath() + '/'
                        + libraryFile.getName();
            }

            jpfConfig.listener = JPFConfig.SYMBOLIC_LISTENER;
            jpfConfig.symbolicDebug = JPFConfig.ON;

            jpfConfig.searchMultipleErrors = JPFConfig.TRUE;
            jpfConfig.decisionProcedure = JPFConfig.DP_CORAL;

            // generate main()
            JavaClassWithMain main = new JavaClassWithMain();
            main.setPackageName(javaClass.getPackage().getName());
            main.setClassName(javaClass.getSimpleName() + '_' + method.getName());

            main.imports().add(javaClass.getName());

            String[] parameterLiterals = new String[parameterTypes.length];

            int i = 0;
            for (Class<?> parameterType : parameterTypes) {
                parameterLiterals[i] = SpfGenerator.getParameterLiteral(parameterType);
                i++;
            }

            main.codeLines().add(javaClass.getSimpleName() + '.' + method.getName() + '('
                    + StringUtils.join(parameterLiterals, ", ") + ");");

            // save files
            String relativePath = JavaFileUtils.packageNameToFilename(main.getFullClassName());
            String relativePathJPF = relativePath + '.' + JPFConfig.JPF_CONFIG_EXTENSION;
            String relativePathMain = relativePath + '.' + JavaFileUtils.JAVA_SOURCE_EXTENSION;

            File targetJPFFile = new File(getRunnerProjectSettings().getGeneratedDirectory(), relativePathJPF);
            FileUtils.forceMkdir(targetJPFFile.getParentFile());
            FileUtils.write(targetJPFFile, jpfConfig.generate().toString());

            File targetMainFile = new File(getRunnerProjectSettings().getGeneratedDirectory(),
                    relativePathMain);
            FileUtils.forceMkdir(targetMainFile.getParentFile());
            FileUtils.write(targetMainFile, main.generateJavaCode().toString());
        }
    }
}

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

public static boolean isBeanPropertyWriteMethod(Method method) {
    return method != null && Modifier.isPublic(method.getModifiers())
            && !Modifier.isStatic(method.getModifiers()) && method.getDeclaringClass() != Object.class
            && method.getParameterTypes().length == 1 && method.getName().startsWith("set")
            && method.getName().length() > 3;
}

From source file:io.micrometer.spring.scheduling.ScheduledMethodMetrics.java

@Around("execution (@org.springframework.scheduling.annotation.Scheduled  * *.*(..))")
public Object timeScheduledOperation(ProceedingJoinPoint pjp) throws Throwable {
    Method method = ((MethodSignature) pjp.getSignature()).getMethod();
    String signature = pjp.getSignature().toShortString();

    if (method.getDeclaringClass().isInterface()) {
        try {/*from  w  w  w.j a v a 2 s  .c om*/
            method = pjp.getTarget().getClass().getDeclaredMethod(pjp.getSignature().getName(),
                    method.getParameterTypes());
        } catch (final SecurityException | NoSuchMethodException e) {
            logger.warn("Unable to perform metrics timing on " + signature, e);
            return pjp.proceed();
        }
    }

    Timer shortTaskTimer = null;
    LongTaskTimer longTaskTimer = null;

    for (Timed timed : TimedUtils.findTimedAnnotations(method)) {
        if (timed.longTask())
            longTaskTimer = LongTaskTimer.builder(timed.value()).tags(timed.extraTags())
                    .description("Timer of @Scheduled long task").register(registry);
        else {
            Timer.Builder timerBuilder = Timer.builder(timed.value()).tags(timed.extraTags())
                    .description("Timer of @Scheduled task");

            if (timed.percentiles().length > 0) {
                timerBuilder = timerBuilder.publishPercentiles(timed.percentiles());
            }

            shortTaskTimer = timerBuilder.register(registry);
        }
    }

    if (shortTaskTimer != null && longTaskTimer != null) {
        final Timer finalTimer = shortTaskTimer;
        //noinspection NullableProblems
        return recordThrowable(longTaskTimer, () -> recordThrowable(finalTimer, pjp::proceed));
    } else if (shortTaskTimer != null) {
        //noinspection NullableProblems
        return recordThrowable(shortTaskTimer, pjp::proceed);
    } else if (longTaskTimer != null) {
        //noinspection NullableProblems
        return recordThrowable(longTaskTimer, pjp::proceed);
    }

    return pjp.proceed();
}

From source file:com.zero.service.impl.BaseServiceImpl.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void copyProperties(Object source, Object target) throws BeansException {
    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");

    PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(target.getClass());
    for (PropertyDescriptor targetPd : targetPds) {
        if (targetPd.getWriteMethod() != null) {
            PropertyDescriptor sourcePd = BeanUtils.getPropertyDescriptor(source.getClass(),
                    targetPd.getName());
            if (sourcePd != null && sourcePd.getReadMethod() != null) {
                try {
                    Method readMethod = sourcePd.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }/*w w w.  j a v  a2 s  .  c om*/
                    Object sourceValue = readMethod.invoke(source);
                    Object targetValue = readMethod.invoke(target);
                    if (sourceValue != null && targetValue != null && targetValue instanceof Collection) {
                        Collection collection = (Collection) targetValue;
                        collection.clear();
                        collection.addAll((Collection) sourceValue);
                    } else {
                        Method writeMethod = targetPd.getWriteMethod();
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        writeMethod.invoke(target, sourceValue);
                    }
                } catch (Throwable ex) {
                    throw new FatalBeanException("Could not copy properties from source to target", ex);
                }
            }
        }
    }
}

From source file:ch.rasc.wampspring.method.InvocableWampHandlerMethod.java

/**
 * Assert that the target bean class is an instance of the class where the given
 * method is declared. In some cases the actual controller instance at request-
 * processing time may be a JDK dynamic proxy (lazy initialization, prototype beans,
 * and others). {@code @Controller}'s that require proxying should prefer class-based
 * proxy mechanisms.//from  w  ww .  j ava2s  .c o  m
 */
private void assertTargetBean(Method method, Object targetBean, Object[] args) {
    Class<?> methodDeclaringClass = method.getDeclaringClass();
    Class<?> targetBeanClass = targetBean.getClass();
    if (!methodDeclaringClass.isAssignableFrom(targetBeanClass)) {
        String msg = "The mapped controller method class '" + methodDeclaringClass.getName()
                + "' is not an instance of the actual controller bean instance '" + targetBeanClass.getName()
                + "'. If the controller requires proxying "
                + "(e.g. due to @Transactional), please use class-based proxying.";
        throw new IllegalStateException(getInvocationErrorMessage(msg, args));
    }
}

From source file:com.weibo.api.motan.proxy.RefererInvocationHandler.java

/**
 * tostring,equals,hashCode,finalize??/*w  w w .j av a  2  s . c om*/
 *
 * @param method
 * @return
 */
public boolean isLocalMethod(Method method) {
    if (method.getDeclaringClass().equals(Object.class)) {
        try {
            Method interfaceMethod = clz.getDeclaredMethod(method.getName(), method.getParameterTypes());
            return false;
        } catch (Exception e) {
            return true;
        }
    }
    return false;
}

From source file:org.apache.openjpa.enhance.PCSubclassValidator.java

private BCMethod getBCMethod(Method meth) {
    BCClass bc = pc.getProject().loadClass(meth.getDeclaringClass());
    return bc.getDeclaredMethod(meth.getName(), meth.getParameterTypes());
}

From source file:net.groupbuy.service.impl.BaseServiceImpl.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void copyProperties(Object source, Object target, String[] ignoreProperties) throws BeansException {
    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");

    PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(target.getClass());
    List<String> ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;
    for (PropertyDescriptor targetPd : targetPds) {
        if (targetPd.getWriteMethod() != null
                && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {
            PropertyDescriptor sourcePd = BeanUtils.getPropertyDescriptor(source.getClass(),
                    targetPd.getName());
            if (sourcePd != null && sourcePd.getReadMethod() != null) {
                try {
                    Method readMethod = sourcePd.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }/*w w w . j  av  a  2  s .  com*/
                    Object sourceValue = readMethod.invoke(source);
                    Object targetValue = readMethod.invoke(target);
                    if (sourceValue != null && targetValue != null && targetValue instanceof Collection) {
                        Collection collection = (Collection) targetValue;
                        collection.clear();
                        collection.addAll((Collection) sourceValue);
                    } else {
                        Method writeMethod = targetPd.getWriteMethod();
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        writeMethod.invoke(target, sourceValue);
                    }
                } catch (Throwable ex) {
                    throw new FatalBeanException("Could not copy properties from source to target", ex);
                }
            }
        }
    }
}

From source file:com.jayway.jaxrs.hateoas.DefaultHateoasContext.java

private void mapClass(Class<?> clazz, String path) {

    if (!isInitialized(clazz)) {
        logger.info("Mapping class {}", clazz);

        if (path.endsWith("/")) {
            path = StringUtils.removeEnd(path, "/");
        }//from w  w w  . j a  va  2  s  .  c  o  m

        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            if (!method.getDeclaringClass().equals(Object.class)) {
                mapMethod(clazz, path, method);
            }
        }
    } else {
        logger.info("Class {} already mapped. Skipped mapping.", clazz);
    }
}