Example usage for java.lang.reflect Method getModifiers

List of usage examples for java.lang.reflect Method getModifiers

Introduction

In this page you can find the example usage for java.lang.reflect Method getModifiers.

Prototype

@Override
public int getModifiers() 

Source Link

Usage

From source file:cz.cuni.mff.d3s.tools.perfdoc.server.measuring.codegen.CodeGenerator.java

private void makeAndCompileGeneratorCode(BenchmarkSetting setting) throws CompileException, IOException {

    MethodReflectionInfo mrInfo = (MethodReflectionInfo) setting.getWorkload();
    Method generator = mrInfo.getMethod();

    VelocityContext context = new VelocityContext();

    context.put("gFunction", generator);
    context.put("gFunctionIsStatic", Modifier.isStatic(generator.getModifiers()));
    context.put("gClass", mrInfo.getContainingClass().getName());

    //TODO if enum - need to prefix with full name + dot
    context.put("gParameterType", generator.getParameterTypes());

    context.put("gArgument", setting.getWorkloadArguments().getValues());

    writeCode(context, templateGeneratorName);

    String javaSourceName = javaDestinationDir + directoryName + "/" + templateGeneratorName + ".java";
    String javaClassDirectory = compiledClassDestinationDir + directoryName;

    List<String> classPaths = getCompilationClassPaths();
    classPaths.add(javaClassDirectory);//from w  w  w.j a va  2 s.c  o m

    Compiler.compile(javaSourceName, classPaths);
}

From source file:net.mojodna.sprout.Sprout.java

public final void setBeanFactory(final BeanFactory factory) throws BeansException {
    if (!factory.isSingleton(beanName)) {
        log.warn(getClass().getName() + " must be defined with singleton=\"true\" in order to self-register.");
        return;//from   www  .j  a  v a 2s .  c  o m
    }

    final String pkgName = getClass().getPackage().getName();
    final String path = pkgName.substring(pkgName.indexOf(PACKAGE_DELIMITER) + PACKAGE_DELIMITER.length())
            .replace('.', '/') + "/";

    if (factory instanceof AbstractBeanFactory) {
        final AbstractBeanFactory dlbf = (AbstractBeanFactory) factory;

        final Collection<Method> methods = SproutUtils.getDeclaredMethods(getClass(), Sprout.class);

        // register beans for each url
        log.debug("Registering paths...");
        for (final Iterator<Method> i = methods.iterator(); i.hasNext();) {
            final Method method = i.next();
            String name = method.getName();
            if (Modifier.isPublic(method.getModifiers())
                    && method.getReturnType().equals(ActionForward.class)) {
                if (name.equals("publick"))
                    name = "public";
                final String url = path + name.replaceAll("([A-Z])", "_$1").toLowerCase();
                log.debug(url);
                if (!ArrayUtils.contains(dlbf.getAliases(beanName), url))
                    dlbf.registerAlias(beanName, url);
            }
        }
    } else {
        log.warn("Unable to self-register; factory bean was of an unsupported type.");
        throw new BeanNotOfRequiredTypeException(beanName, AbstractBeanFactory.class, factory.getClass());
    }
}

From source file:com.nxttxn.vramel.impl.converter.AnnotationTypeConverterLoader.java

private CachingInjector<?> handleHasConverterAnnotation(TypeConverterRegistry registry, Class<?> type,
        CachingInjector<?> injector, Method method) {
    if (isValidConverterMethod(method)) {
        int modifiers = method.getModifiers();
        if (isAbstract(modifiers) || !isPublic(modifiers)) {
            LOG.warn("Ignoring bad converter on type: " + type.getCanonicalName() + " method: " + method
                    + " as a converter method is not a public and concrete method");
        } else {/*  w w  w.j  a v a2s  . c  om*/
            Class<?> toType = method.getReturnType();
            if (toType.equals(Void.class)) {
                LOG.warn("Ignoring bad converter on type: " + type.getCanonicalName() + " method: " + method
                        + " as a converter method returns a void method");
            } else {
                Class<?> fromType = method.getParameterTypes()[0];
                if (isStatic(modifiers)) {
                    registerTypeConverter(registry, method, toType, fromType,
                            new StaticMethodTypeConverter(method));
                } else {
                    if (injector == null) {
                        injector = new CachingInjector<Object>(registry, CastUtils.cast(type, Object.class));
                    }
                    registerTypeConverter(registry, method, toType, fromType,
                            new InstanceMethodTypeConverter(injector, method, registry));
                }
            }
        }
    } else {
        LOG.warn("Ignoring bad converter on type: " + type.getCanonicalName() + " method: " + method
                + " as a converter method should have one parameter");
    }
    return injector;
}

From source file:cz.cuni.mff.d3s.tools.perfdoc.server.measuring.codegen.CodeGenerator.java

private void makeAndCompileMethodCode(BenchmarkSetting setting) throws CompileException, IOException {

    MethodReflectionInfo mrInfo = (MethodReflectionInfo) setting.getTestedMethod();
    Method testedMethod = mrInfo.getMethod();

    VelocityContext context = new VelocityContext();

    context.put("mFunction", testedMethod);
    context.put("mFunctionIsStatic", Modifier.isStatic(testedMethod.getModifiers()));
    context.put("mClass", mrInfo.getContainingClass().getName());
    context.put("mFunctionIsNotVoid", !(testedMethod.getReturnType().equals(Void.TYPE)));

    writeCode(context, templateMethodName);

    String javaSourceName = javaDestinationDir + directoryName + "/" + templateMethodName + ".java";
    String javaClassDirectory = compiledClassDestinationDir + directoryName;

    List<String> classPaths = getCompilationClassPaths();
    classPaths.add(javaClassDirectory);/*from w w w .  ja v a  2s . c  o  m*/

    Compiler.compile(javaSourceName, classPaths);
}

From source file:com.duy.pascal.interperter.libraries.PascalLibraryManager.java

public void addMethodFromLibrary(Class<? extends IPascalLibrary> clazz, @Nullable Object instance,
        @Nullable LineNumber line) throws PermissionDeniedException {

    if (instance instanceof IAndroidLibrary && mHandler != null && mHandler.getApplicationContext() != null) {
        String[] permissions = ((IAndroidLibrary) instance).needPermission();
        for (String permission : permissions) {
            if (DLog.ANDROID) {
                int i = ActivityCompat.checkSelfPermission(mHandler.getApplicationContext(), permission);
                if (i != PackageManager.PERMISSION_GRANTED) {
                    throw new PermissionDeniedException(((IAndroidLibrary) instance).getName(), permission,
                            line);/*  ww w . j a v a  2 s . c  o m*/
                }
            }
        }
    }

    PascalLibrary library = (PascalLibrary) instance;
    if (library != null) {
        library.declareConstants(mProgram);
        library.declareFunctions(mProgram);
        library.declareTypes(mProgram);
        library.declareVariables(mProgram);
    }

    ArrayList<MethodDeclaration> declarations = METHOD_CACHE.get(clazz);
    if (declarations == null) {
        declarations = new ArrayList<>();
        for (Method method : clazz.getDeclaredMethods()) {
            if (Modifier.isPublic(method.getModifiers()) && !isHiddenSystemMethod(method.getName())) {
                if (AndroidLibraryUtils.getSdkVersion() >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                    if (method.getAnnotation(PascalMethod.class) != null) {
                        PascalMethod annotation = method.getAnnotation(PascalMethod.class);
                        String description = annotation.description();
                        MethodDeclaration methodDecl = new MethodDeclaration(instance, method, description);
                        declarations.add(methodDecl);
                    }
                } else {
                    MethodDeclaration methodDeclaration = new MethodDeclaration(instance, method);
                    declarations.add(methodDeclaration);
                }
            }
        }
        Collections.sort(declarations, new Comparator<AbstractFunction>() {
            @Override
            public int compare(AbstractFunction o1, AbstractFunction o2) {
                if (o1.getName().equals(o2.getName())) {
                    ArgumentType[] types1 = o1.argumentTypes();
                    ArgumentType[] types2 = o2.argumentTypes();
                    if (types1.length != types2.length) {
                        return -1;
                    }

                    for (int i = 0; i < types1.length; i++) {
                        Class<?> t1Class = types1[i].getRuntimeClass();
                        Class<?> t2Class = types2[i].getRuntimeClass();
                        if (t1Class.equals(t2Class)) {
                            continue;
                        }

                        if (TypeConverter.isPrimitive(t1Class) && TypeConverter.isPrimitive(t2Class)) {
                            if (!types1[i].equals(types2[i])) {
                                if (TypeConverter.isLowerThanPrecedence(t1Class, t2Class)) {
                                    return -1;
                                }
                            }
                        } else {
                            return -1;
                        }
                    }
                }
                return o1.getName().compareTo(o2.getName());
            }
        });
        METHOD_CACHE.put(clazz, declarations);
    } else {
        for (MethodDeclaration declaration : declarations) {
            declaration.setInstance(instance);
        }
    }
    for (AbstractFunction declaration : declarations) {
        mProgram.declareFunction(declaration);
    }
}

From source file:com.nxttxn.vramel.impl.converter.AnnotationTypeConverterLoader.java

private CachingInjector<?> handleHasFallbackConverterAnnotation(TypeConverterRegistry registry, Class<?> type,
        CachingInjector<?> injector, Method method) {
    if (isValidFallbackConverterMethod(method)) {
        int modifiers = method.getModifiers();
        if (isAbstract(modifiers) || !isPublic(modifiers)) {
            LOG.warn("Ignoring bad fallback converter on type: " + type.getCanonicalName() + " method: "
                    + method + " as a fallback converter method is not a public and concrete method");
        } else {//from w w  w  . java  2 s  .c  o m
            Class<?> toType = method.getReturnType();
            if (toType.equals(Void.class)) {
                LOG.warn("Ignoring bad fallback converter on type: " + type.getCanonicalName() + " method: "
                        + method + " as a fallback converter method returns a void method");
            } else {
                if (isStatic(modifiers)) {
                    registerFallbackTypeConverter(registry,
                            new StaticMethodFallbackTypeConverter(method, registry), method);
                } else {
                    if (injector == null) {
                        injector = new CachingInjector<Object>(registry, CastUtils.cast(type, Object.class));
                    }
                    registerFallbackTypeConverter(registry,
                            new InstanceMethodFallbackTypeConverter(injector, method, registry), method);
                }
            }
        }
    } else {
        LOG.warn("Ignoring bad fallback converter on type: " + type.getCanonicalName() + " method: " + method
                + " as a fallback converter method should have one parameter");
    }
    return injector;
}

From source file:org.codehaus.groovy.grails.commons.DefaultGrailsControllerClass.java

private void flowStrategy(Collection<String> closureNames) {

    for (PropertyDescriptor propertyDescriptor : getPropertyDescriptors()) {
        Method readMethod = propertyDescriptor.getReadMethod();
        if (readMethod != null && !Modifier.isStatic(readMethod.getModifiers())) {
            final Class<?> propertyType = propertyDescriptor.getPropertyType();
            if ((propertyType == Object.class || propertyType == Closure.class)
                    && propertyDescriptor.getName().endsWith(FLOW_SUFFIX)) {
                String closureName = propertyDescriptor.getName();
                String flowId = closureName.substring(0, closureName.length() - FLOW_SUFFIX.length());
                flows.put(flowId, propertyDescriptor);
                closureNames.add(flowId);
                configureMappingForMethodAction(flowId);
            }/*from   w ww  .  jav a  2  s .  com*/
        }
    }
    if (!isReadableProperty(defaultActionName) && closureNames.size() == 1) {
        defaultActionName = closureNames.iterator().next();
    }
}

From source file:com.weibo.api.motan.config.AbstractConfig.java

@Override
public String toString() {
    try {//from  w w  w.j a  va 2s  .com
        StringBuilder buf = new StringBuilder();
        buf.append("<motan:");
        buf.append(getTagName(getClass()));
        Method[] methods = getClass().getMethods();
        for (Method method : methods) {
            try {
                String name = method.getName();
                if ((name.startsWith("get") || name.startsWith("is")) && !"getClass".equals(name)
                        && !"get".equals(name) && !"is".equals(name) && Modifier.isPublic(method.getModifiers())
                        && method.getParameterTypes().length == 0 && isPrimitive(method.getReturnType())) {
                    int i = name.startsWith("get") ? 3 : 2;
                    String key = name.substring(i, i + 1).toLowerCase() + name.substring(i + 1);
                    Object value = method.invoke(this);
                    if (value != null) {
                        buf.append(" ");
                        buf.append(key);
                        buf.append("=\"");
                        buf.append(value);
                        buf.append("\"");
                    }
                }
            } catch (Exception e) {
                LoggerUtil.warn(e.getMessage(), e);
            }
        }
        buf.append(" />");
        return buf.toString();
    } catch (Throwable t) { // 
        LoggerUtil.warn(t.getMessage(), t);
        return super.toString();
    }
}

From source file:org.hibernate.tuple.entity.PojoEntityTuplizer.java

/**
 * {@inheritDoc}/*from ww  w . j  a  va2 s.  c o  m*/
 */
protected ProxyFactory buildProxyFactory(PersistentClass persistentClass, Getter idGetter, Setter idSetter) {
    // determine the id getter and setter methods from the proxy interface (if any)
    // determine all interfaces needed by the resulting proxy
    HashSet proxyInterfaces = new HashSet();
    proxyInterfaces.add(HibernateProxy.class);

    Class mappedClass = persistentClass.getMappedClass();
    Class proxyInterface = persistentClass.getProxyInterface();

    if (proxyInterface != null && !mappedClass.equals(proxyInterface)) {
        if (!proxyInterface.isInterface()) {
            throw new MappingException(
                    "proxy must be either an interface, or the class itself: " + getEntityName());
        }
        proxyInterfaces.add(proxyInterface);
    }

    if (mappedClass.isInterface()) {
        proxyInterfaces.add(mappedClass);
    }

    Iterator iter = persistentClass.getSubclassIterator();
    while (iter.hasNext()) {
        Subclass subclass = (Subclass) iter.next();
        Class subclassProxy = subclass.getProxyInterface();
        Class subclassClass = subclass.getMappedClass();
        if (subclassProxy != null && !subclassClass.equals(subclassProxy)) {
            if (!proxyInterface.isInterface()) {
                throw new MappingException(
                        "proxy must be either an interface, or the class itself: " + subclass.getEntityName());
            }
            proxyInterfaces.add(subclassProxy);
        }
    }

    Iterator properties = persistentClass.getPropertyIterator();
    Class clazz = persistentClass.getMappedClass();
    while (properties.hasNext()) {
        Property property = (Property) properties.next();
        Method method = property.getGetter(clazz).getMethod();
        if (method != null && Modifier.isFinal(method.getModifiers())) {
            log.error("Getters of lazy classes cannot be final: " + persistentClass.getEntityName() + "."
                    + property.getName());
        }
        method = property.getSetter(clazz).getMethod();
        if (method != null && Modifier.isFinal(method.getModifiers())) {
            log.error("Setters of lazy classes cannot be final: " + persistentClass.getEntityName() + "."
                    + property.getName());
        }
    }

    Method idGetterMethod = idGetter == null ? null : idGetter.getMethod();
    Method idSetterMethod = idSetter == null ? null : idSetter.getMethod();

    Method proxyGetIdentifierMethod = idGetterMethod == null || proxyInterface == null ? null
            : ReflectHelper.getMethod(proxyInterface, idGetterMethod);
    Method proxySetIdentifierMethod = idSetterMethod == null || proxyInterface == null ? null
            : ReflectHelper.getMethod(proxyInterface, idSetterMethod);

    ProxyFactory pf = buildProxyFactoryInternal(persistentClass, idGetter, idSetter);
    try {
        pf.postInstantiate(getEntityName(), mappedClass, proxyInterfaces, proxyGetIdentifierMethod,
                proxySetIdentifierMethod,
                persistentClass.hasEmbeddedIdentifier()
                        ? (AbstractComponentType) persistentClass.getIdentifier().getType()
                        : null);
    } catch (HibernateException he) {
        log.warn("could not create proxy factory for:" + getEntityName(), he);
        pf = null;
    }
    return pf;
}

From source file:org.batoo.jpa.parser.impl.metadata.type.ManagedTypeMetadatImpl.java

/**
 * Infers and returns the access type based on all persistence annotations being on fields or methods and parent parent access type.
 * //from  w  w  w. ja  va2  s.co m
 * @param parentAccessType
 *            the parent access type
 * @return the inferred access type
 * 
 * @since 2.0.0
 */
private AccessType inferAccessType(AccessType parentAccessType) {
    boolean methodsHasAnnotations = false;
    boolean fieldsHasAnnotations = false;

    final List<String> alternated = Lists.newArrayList();

    final Field[] fields = this.clazz.getDeclaredFields();
    final Method[] methods = this.clazz.getDeclaredMethods();

    // find the alternated ones with @Access
    for (final Method m : methods) {
        // skip static and private methods.
        final int mods = m.getModifiers();
        if (Modifier.isStatic(mods) || !Modifier.isPublic(mods) || m.isBridge() || m.isSynthetic()) {
            continue;
        }

        if ((m.getParameterTypes().length != 0) || (m.getReturnType() == null)) {
            continue;
        }

        final Access access = m.getAnnotation(Access.class);
        if (access != null) {
            final String name = m.getName();
            if ((m.getReturnType() == boolean.class) && name.startsWith("is")) {
                alternated.add(StringUtils.capitalize(name.substring(2)));
            } else if (name.startsWith("get")) {
                alternated.add(StringUtils.capitalize(name.substring(3)));
            }
        }
    }

    for (final Field f : fields) {
        final Access access = f.getAnnotation(Access.class);

        if (access != null) {
            alternated.add(StringUtils.capitalize(f.getName()));
        }
    }

    // check methods
    for (final Method m : methods) {
        for (final Annotation a : m.getAnnotations()) {
            // ignore @Access(PROPERTY)
            if (a instanceof Access) {
                if (((Access) a).value() != AccessType.PROPERTY) {
                    continue;
                }
            }

            // ignore @Transient
            if (a instanceof Transient) {
                continue;
            }

            if ((m.getReturnType() == null) || (m.getParameterTypes().length > 0)) {
                continue;
            }

            String name = a.annotationType().getName();
            // ignore the listener annotations
            if (name.startsWith("javax.persistence.Post") || name.startsWith("javax.persistence.Pre")) {
                continue;
            }

            if (name.startsWith("javax.persistence") || name.startsWith("org.batoo.jpa.annotation")) {
                name = m.getName();

                if ((boolean.class == m.getReturnType()) || name.startsWith("is")) {
                    name = name.substring(2);
                } else if (name.startsWith("get")) {
                    name = name.substring(3);
                }

                if (alternated.contains(StringUtils.capitalize(name))) {
                    continue;
                }

                methodsHasAnnotations = true;
                break;
            }
        }
    }

    // check fields
    for (final Field f : fields) {
        for (final Annotation a : f.getAnnotations()) {
            // ignore @Access(FIELD)
            if (a instanceof Access) {
                if (((Access) a).value() != AccessType.FIELD) {
                    continue;
                }
            }

            // ignore @Transient
            if (a instanceof Transient) {
                continue;
            }

            final String name = a.annotationType().getName();
            if (name.startsWith("javax.persistence") || name.startsWith("org.batoo.jpa.annotation")) {
                if (alternated.contains(StringUtils.capitalize(f.getName()))) {
                    continue;
                }

                fieldsHasAnnotations = true;
                break;
            }
        }
    }

    if (fieldsHasAnnotations && methodsHasAnnotations) {
        throw new PersistenceException(
                "At least one field and one method has persistence annotations: " + this.clazz.getName());
    }

    if (methodsHasAnnotations) {
        return AccessType.PROPERTY;
    }

    if (fieldsHasAnnotations) {
        return AccessType.FIELD;
    }

    if (parentAccessType != null) {
        return parentAccessType;
    }

    return AccessType.FIELD;
}