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:org.apache.openjpa.persistence.AnnotationPersistenceMetaDataParser.java

/**
 * Parse callback methods into the given array, and return that array,
 * creating one if null. Each index into the array is a collection of
 * callback adapters for that numeric event type.
 *
 * @param sups whether to scan superclasses
 * @param listener whether this is a listener or not
 *//*from   www.  j  av a 2 s. c om*/
public static Collection<LifecycleCallbacks>[] parseCallbackMethods(Class<?> cls,
        Collection<LifecycleCallbacks>[] callbacks, boolean sups, boolean listener, MetaDataRepository repos) {

    if (cls == null)
        throw new IllegalArgumentException("cls cannot be null");

    // first sort / filter based on inheritance
    Set<Method> methods = new TreeSet<Method>(MethodComparator.getInstance());

    int mods;
    Class<?> sup = cls;
    MethodKey key;
    Set<MethodKey> seen = new HashSet<MethodKey>();
    do {
        for (Method m : (Method[]) AccessController
                .doPrivileged(J2DoPrivHelper.getDeclaredMethodsAction(sup))) {
            mods = m.getModifiers();
            if (Modifier.isStatic(mods) || Modifier.isFinal(mods) || Object.class.equals(m.getDeclaringClass()))
                continue;

            key = new MethodKey(m);
            if (!seen.contains(key)) {
                methods.add(m);
                seen.add(key);
            }
        }
        sup = sup.getSuperclass();
    } while (sups && !Object.class.equals(sup));

    OpenJPAConfiguration conf = repos.getConfiguration();
    for (Method m : methods) {
        for (Annotation anno : (Annotation[]) AccessController
                .doPrivileged(J2DoPrivHelper.getDeclaredAnnotationsAction(m))) {
            MetaDataTag tag = _tags.get(anno.annotationType());
            if (tag == null)
                continue;
            int[] events = MetaDataParsers.getEventTypes(tag, conf);
            if (events == null)
                continue;

            if (callbacks == null)
                callbacks = (Collection<LifecycleCallbacks>[]) new Collection[LifecycleEvent.ALL_EVENTS.length];

            for (int i = 0; i < events.length; i++) {
                int e = events[i];
                if (callbacks[e] == null)
                    callbacks[e] = new ArrayList<LifecycleCallbacks>(3);
                MetaDataParsers.validateMethodsForSameCallback(cls, callbacks[e], m, tag, conf, repos.getLog());
                if (listener) {
                    callbacks[e].add(new BeanLifecycleCallbacks(cls, m, false));
                } else {
                    callbacks[e].add(new MethodLifecycleCallbacks(m, false));
                }
            }
        }
    }
    return callbacks;
}

From source file:org.apache.felix.webconsole.AbstractWebConsolePlugin.java

/**
 * Returns a method which is called on the
 * {@link #getResourceProvider() resource provider} class to return an URL
 * to a resource which may be spooled when requested. The method has the
 * following signature://from  w ww .  jav a  2s .c  o  m
 * <pre>
 * [modifier] URL getResource(String path);
 * </pre>
 * Where the <i>[modifier]</i> may be <code>public</code>, <code>protected</code>
 * or <code>private</code> (if the method is declared in the class of the
 * resource provider). It is suggested to use the <code>private</code>
 * modifier if the method is declared in the resource provider class or
 * the <code>protected</code> modifier if the method is declared in a
 * base class of the resource provider.
 *
 * @return The <code>getResource(String)</code> method or <code>null</code>
 *      if the {@link #getResourceProvider() resource provider} is
 *      <code>null</code> or does not provide such a method.
 */
private final Method getGetResourceMethod() {
    // return what we know of the getResourceMethod, if we already checked
    if (getResourceMethodChecked) {
        return getResourceMethod;
    }

    Method tmpGetResourceMethod = null;
    Object resourceProvider = getResourceProvider();
    if (resourceProvider != null) {
        try {
            Class cl = resourceProvider.getClass();
            while (tmpGetResourceMethod == null && cl != Object.class) {
                Method[] methods = cl.getDeclaredMethods();
                for (int i = 0; i < methods.length; i++) {
                    Method m = methods[i];
                    if (GET_RESOURCE_METHOD_NAME.equals(m.getName()) && m.getParameterTypes().length == 1
                            && m.getParameterTypes()[0] == String.class && m.getReturnType() == URL.class) {
                        // ensure modifier is protected or public or the private
                        // method is defined in the plugin class itself
                        int mod = m.getModifiers();
                        if (Modifier.isProtected(mod) || Modifier.isPublic(mod)
                                || (Modifier.isPrivate(mod) && cl == resourceProvider.getClass())) {
                            m.setAccessible(true);
                            tmpGetResourceMethod = m;
                            break;
                        }
                    }
                }
                cl = cl.getSuperclass();
            }
        } catch (Throwable t) {
            tmpGetResourceMethod = null;
        }
    }

    // set what we have found and prevent future lookups
    getResourceMethod = tmpGetResourceMethod;
    getResourceMethodChecked = true;

    // now also return the method
    return getResourceMethod;
}

From source file:name.yumaa.ChromeLogger4J.java

/**
 * Converts an object to a better format for logging
 * @param object    variable to conver//  w  w  w.  j a  va  2  s. c  o m
 * @param depth     recursion depth
 * @return converted object, ready to put to JSON
 */
private Object convert(Object object, int depth) {
    // *** return simple types as is ***
    if (object == null || object instanceof String || object instanceof Number || object instanceof Boolean)
        return object;

    // *** other simple types ***

    if (object instanceof Character || object instanceof StringBuffer || object instanceof StringBuilder
            || object instanceof Currency || object instanceof Date || object instanceof Locale)
        return object.toString();

    if (object instanceof Calendar)
        return ((Calendar) object).getTime().toString();

    if (object instanceof SimpleDateFormat)
        return ((SimpleDateFormat) object).toPattern();

    // check recursion depth
    if (depth > this.depth)
        return "d>" + this.depth;

    // mark this object as processed so we don't convert it twice and it
    // also avoid recursion when objects refer to each other
    processed.add(object);

    // *** not so simple types, but we can foreach it ***

    if (object instanceof Map) {
        JSONObject jobject = new JSONObject();
        for (Object key : ((Map<Object, Object>) object).keySet()) {
            Object value = ((Map<Object, Object>) object).get(key);
            addValue(jobject, key.toString(), value, depth);
        }
        return jobject;
    }

    if (object instanceof Collection) {
        JSONArray jobject = new JSONArray();
        for (Object value : (Collection<Object>) object)
            addValue(jobject, value, depth);
        return jobject;
    }

    if (object instanceof Iterable) {
        JSONArray jobject = new JSONArray();
        for (Object value : (Iterable<Object>) object)
            addValue(jobject, value, depth);
        return jobject;
    }

    if (object instanceof Object[]) {
        JSONArray jobject = new JSONArray();
        for (Object value : (Object[]) object)
            addValue(jobject, value, depth);
        return jobject;
    }

    // *** object of unknown type ***

    JSONObject jobject = new JSONObject();

    Class<?> cls = object.getClass();
    jobject.put("___class_name", cls.getName()); // add the class name
    jobject.put("___toString()", object.toString()); // and to string representation

    if (!this.reflect)
        return jobject;

    // get all properties using reflection
    if (this.reflectfields) {
        try {
            for (Field field : cls.getDeclaredFields()) {
                Boolean access = field.isAccessible();
                field.setAccessible(true);

                int mod = field.getModifiers();
                String key = getKey(mod, field.getName());
                Object value;
                try {
                    value = field.get(object);
                } catch (Exception e) {
                    value = e.toString();
                }

                field.setAccessible(access);

                if (!this.reflectprivate && (Modifier.isPrivate(mod) || Modifier.isProtected(mod)))
                    continue;
                if (!this.reflectstatic && Modifier.isStatic(mod))
                    continue;

                addValue(jobject, key, value, depth);
            }
        } catch (SecurityException e) {
        }
    }

    // get all methods using reflection
    if (this.reflectmethods) {
        try {
            JSONObject methods = new JSONObject();
            for (Method method : cls.getDeclaredMethods()) {
                Boolean access = method.isAccessible();
                method.setAccessible(true);

                Class<?>[] params = method.getParameterTypes();
                StringBuilder parameters = new StringBuilder("");
                for (int i = 0, j = params.length; i < j; i++) {
                    parameters.append(params[i].getName());
                    if (i + 1 < j)
                        parameters.append(", ");
                }
                int mod = method.getModifiers();
                String key = getKey(mod, method.getName() + "(" + parameters.toString() + ")");
                String value = method.getReturnType().getName();

                method.setAccessible(access);

                if (!this.reflectprivate && (Modifier.isPrivate(mod) || Modifier.isProtected(mod)))
                    continue;
                if (!this.reflectstatic && Modifier.isStatic(mod))
                    continue;

                methods.put(key, value);
            }
            jobject.put("___methods", methods);
        } catch (SecurityException e) {
        }
    }

    return jobject;
}

From source file:org.compass.annotations.config.binding.AnnotationsMappingBinding.java

/**
 * Recursivly process the class to find all it's annotations. Lower level
 * class/interfaces with annotations will be added first.
 *//*  w  ww.  j  a v  a2s  . co  m*/
private void processAnnotatedClass(Class<?> clazz) {
    if (clazz.equals(Class.class)) {
        return;
    }
    Class<?> superClazz = clazz.getSuperclass();
    if (superClazz != null && !superClazz.equals(Object.class)) {
        processAnnotatedClass(superClazz);
    }
    Class<?>[] interfaces = clazz.getInterfaces();
    for (Class<?> anInterface : interfaces) {
        processAnnotatedClass(anInterface);
    }

    SearchableConstant searchableConstant = clazz.getAnnotation(SearchableConstant.class);
    if (searchableConstant != null) {
        bindConstantMetaData(searchableConstant);
    }

    SearchableConstants searchableConstants = clazz.getAnnotation(SearchableConstants.class);
    if (searchableConstants != null) {
        for (SearchableConstant metaData : searchableConstants.value()) {
            bindConstantMetaData(metaData);
        }
    }

    SearchableDynamicMetaData searchableDynamicMetaData = clazz.getAnnotation(SearchableDynamicMetaData.class);
    if (searchableDynamicMetaData != null) {
        bindDynamicMetaData(searchableDynamicMetaData);
    }
    SearchableDynamicMetaDatas searchableDynamicMetaDatas = clazz
            .getAnnotation(SearchableDynamicMetaDatas.class);
    if (searchableDynamicMetaDatas != null) {
        for (SearchableDynamicMetaData metaData : searchableDynamicMetaDatas.value()) {
            bindDynamicMetaData(metaData);
        }
    }

    // handles recursive extends and the original extend
    if (clazz.isAnnotationPresent(Searchable.class)) {
        Searchable searchable = clazz.getAnnotation(Searchable.class);
        String[] extend = searchable.extend();
        if (extend.length != 0) {
            ArrayList<String> extendedMappings = new ArrayList<String>();
            if (classMapping.getExtendedAliases() != null) {
                extendedMappings.addAll(Arrays.asList(classMapping.getExtendedAliases()));
            }
            for (String extendedAlias : extend) {
                Alias extendedAliasLookup = valueLookup.lookupAlias(extendedAlias);
                if (extendedAliasLookup == null) {
                    extendedMappings.add(extendedAlias);
                } else {
                    extendedMappings.add(extendedAliasLookup.getName());
                }
            }
            classMapping.setExtendedAliases(extendedMappings.toArray(new String[extendedMappings.size()]));
        }
    }

    // if the super class has Searchable annotation as well, add it to the list of extends
    ArrayList<Class> extendedClasses = new ArrayList<Class>();
    if (clazz.getSuperclass() != null) {
        extendedClasses.add(clazz.getSuperclass());
    }
    extendedClasses.addAll(Arrays.asList(clazz.getInterfaces()));
    for (Class<?> superClass : extendedClasses) {
        if (!superClass.isAnnotationPresent(Searchable.class)) {
            continue;
        }
        Searchable superSearchable = superClass.getAnnotation(Searchable.class);
        String alias = getAliasFromSearchableClass(superClass, superSearchable);
        HashSet<String> extendedMappings = new HashSet<String>();
        if (classMapping.getExtendedAliases() != null) {
            extendedMappings.addAll(Arrays.asList(classMapping.getExtendedAliases()));
        }
        extendedMappings.add(alias);
        classMapping.setExtendedAliases(extendedMappings.toArray(new String[extendedMappings.size()]));
    }

    for (Field field : clazz.getDeclaredFields()) {
        for (Annotation annotation : field.getAnnotations()) {
            processsAnnotatedElement(clazz, field.getName(), "field", field.getType(), field.getGenericType(),
                    annotation, field);
        }
    }
    for (Method method : clazz.getDeclaredMethods()) {
        if (!method.isSynthetic() && !method.isBridge() && !Modifier.isStatic(method.getModifiers())
                && method.getParameterTypes().length == 0 && method.getReturnType() != void.class
                && (method.getName().startsWith("get") || method.getName().startsWith("is"))) {

            for (Annotation annotation : method.getAnnotations()) {
                processsAnnotatedElement(clazz, ClassUtils.getShortNameForMethod(method), "property",
                        method.getReturnType(), method.getGenericReturnType(), annotation, method);
            }
        }
    }
}

From source file:org.apache.axis2.description.java2wsdl.DocLitBareSchemaGenerator.java

@Override
protected Method[] processMethods(Method[] declaredMethods) throws Exception {
    ArrayList<Method> list = new ArrayList<Method>();
    //short the elements in the array
    Arrays.sort(declaredMethods, new MathodComparator());

    // since we do not support overload
    HashMap<String, Method> uniqueMethods = new LinkedHashMap<String, Method>();
    XmlSchemaComplexType methodSchemaType;
    XmlSchemaSequence sequence;//from w  ww .  ja  va  2 s .  c om

    for (Method jMethod : declaredMethods) {
        if (jMethod.isBridge()) {
            continue;
        }
        WebMethodAnnotation methodAnnon = JSR181Helper.INSTANCE.getWebMethodAnnotation(jMethod);
        if (methodAnnon != null) {
            if (methodAnnon.isExclude()) {
                continue;
            }
        }
        String methodName = jMethod.getName();
        // no need to think abt this method , since that is system
        // config method
        if (excludeMethods.contains(methodName)) {
            continue;
        }

        if (uniqueMethods.get(methodName) != null) {
            log.warn("We don't support method overloading. Ignoring [" + methodName + "]");
            continue;
        }

        if (!Modifier.isPublic(jMethod.getModifiers())) {
            // no need to generate Schema for non public methods
            continue;
        }

        boolean addToService = false;
        AxisOperation axisOperation = service.getOperation(new QName(methodName));
        if (axisOperation == null) {
            axisOperation = Utils.getAxisOperationForJmethod(jMethod);
            if (WSDL2Constants.MEP_URI_ROBUST_IN_ONLY.equals(axisOperation.getMessageExchangePattern())) {
                AxisMessage outMessage = axisOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
                if (outMessage != null) {
                    outMessage.setName(methodName + RESULT);
                }
            }
            addToService = true;
        }

        // Maintain a list of methods we actually work with
        list.add(jMethod);
        processException(jMethod, axisOperation);
        uniqueMethods.put(methodName, jMethod);
        //create the schema type for the method wrapper

        uniqueMethods.put(methodName, jMethod);
        Class<?>[] paras = jMethod.getParameterTypes();
        String parameterNames[] = methodTable.getParameterNames(methodName);
        AxisMessage inMessage = axisOperation.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
        if (inMessage != null) {
            inMessage.setName(methodName + "RequestMessage");
        }
        Annotation[][] parameterAnnotation = jMethod.getParameterAnnotations();
        if (paras.length > 1) {
            sequence = new XmlSchemaSequence();
            methodSchemaType = createSchemaTypeForMethodPart(methodName);
            methodSchemaType.setParticle(sequence);
            inMessage.setElementQName(typeTable.getQNamefortheType(methodName));
            service.addMessageElementQNameToOperationMapping(methodSchemaType.getQName(), axisOperation);
            inMessage.setPartName(methodName);
            for (int j = 0; j < paras.length; j++) {
                Class<?> methodParameter = paras[j];
                String parameterName = getParameterName(parameterAnnotation, j, parameterNames);
                if (generateRequestSchema(methodParameter, parameterName, jMethod, sequence)) {
                    break;
                }
            }
        } else if (paras.length == 1) {
            if (paras[0].isArray()) {
                sequence = new XmlSchemaSequence();

                methodSchemaType = createSchemaTypeForMethodPart(methodName);
                methodSchemaType.setParticle(sequence);
                Class<?> methodParameter = paras[0];
                inMessage.setElementQName(typeTable.getQNamefortheType(methodName));
                service.addMessageElementQNameToOperationMapping(methodSchemaType.getQName(), axisOperation);
                inMessage.setPartName(methodName);
                String parameterName = getParameterName(parameterAnnotation, 0, parameterNames);
                if (generateRequestSchema(methodParameter, parameterName, jMethod, sequence)) {
                    break;
                }
            } else {
                String parameterName = getParameterName(parameterAnnotation, 0, parameterNames);
                Class<?> methodParameter = paras[0];
                Method processMethod = processedParameters.get(parameterName);
                if (processMethod != null) {
                    throw new AxisFault(
                            "Inavalid Java class," + " there are two methods [" + processMethod.getName()
                                    + " and " + jMethod.getName() + " ]which have the same parameter names");
                } else {
                    processedParameters.put(parameterName, jMethod);
                    generateSchemaForType(null, methodParameter, parameterName);
                    inMessage.setElementQName(typeTable.getQNamefortheType(parameterName));
                    inMessage.setPartName(parameterName);
                    inMessage.setWrapped(false);
                    service.addMessageElementQNameToOperationMapping(
                            typeTable.getQNamefortheType(parameterName), axisOperation);
                }
            }
        }

        // for its return type
        Class<?> returnType = jMethod.getReturnType();

        if (!"void".equals(jMethod.getReturnType().getName())) {
            AxisMessage outMessage = axisOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
            if (returnType.isArray()) {
                methodSchemaType = createSchemaTypeForMethodPart(jMethod.getName() + RESULT);
                sequence = new XmlSchemaSequence();
                methodSchemaType.setParticle(sequence);
                WebResultAnnotation returnAnnon = JSR181Helper.INSTANCE.getWebResultAnnotation(jMethod);
                String returnName = "return";
                if (returnAnnon != null) {
                    returnName = returnAnnon.getName();
                    if (returnName != null && !"".equals(returnName)) {
                        returnName = "return";
                    }
                }
                if (nonRpcMethods.contains(methodName)) {
                    generateSchemaForType(sequence, null, returnName);
                } else {
                    generateSchemaForType(sequence, returnType, returnName);
                }
            } else {
                generateSchemaForType(null, returnType, methodName + RESULT);
                outMessage.setWrapped(false);
            }
            outMessage.setElementQName(typeTable.getQNamefortheType(methodName + RESULT));
            outMessage.setName(methodName + "ResponseMessage");
            outMessage.setPartName(methodName + RESULT);
            service.addMessageElementQNameToOperationMapping(typeTable.getQNamefortheType(methodName + RESULT),
                    axisOperation);
        }
        if (addToService) {
            service.addOperation(axisOperation);
        }
    }
    return list.toArray(new Method[list.size()]);
}

From source file:org.apache.hadoop.yarn.api.TestPBImplRecords.java

private <R> Map<String, GetSetPair> getGetSetPairs(Class<R> recordClass) throws Exception {
    Map<String, GetSetPair> ret = new HashMap<String, GetSetPair>();
    Method[] methods = recordClass.getDeclaredMethods();
    // get all get methods
    for (int i = 0; i < methods.length; i++) {
        Method m = methods[i];
        int mod = m.getModifiers();
        if (m.getDeclaringClass().equals(recordClass) && Modifier.isPublic(mod) && (!Modifier.isStatic(mod))) {
            String name = m.getName();
            if (name.equals("getProto")) {
                continue;
            }//ww  w. java2s .c  om
            if ((name.length() > 3) && name.startsWith("get") && (m.getParameterTypes().length == 0)) {
                String propertyName = name.substring(3);
                Type valueType = m.getGenericReturnType();
                GetSetPair p = ret.get(propertyName);
                if (p == null) {
                    p = new GetSetPair();
                    p.propertyName = propertyName;
                    p.type = valueType;
                    p.getMethod = m;
                    ret.put(propertyName, p);
                } else {
                    Assert.fail("Multiple get method with same name: " + recordClass + p.propertyName);
                }
            }
        }
    }
    // match get methods with set methods
    for (int i = 0; i < methods.length; i++) {
        Method m = methods[i];
        int mod = m.getModifiers();
        if (m.getDeclaringClass().equals(recordClass) && Modifier.isPublic(mod) && (!Modifier.isStatic(mod))) {
            String name = m.getName();
            if (name.startsWith("set") && (m.getParameterTypes().length == 1)) {
                String propertyName = name.substring(3);
                Type valueType = m.getGenericParameterTypes()[0];
                GetSetPair p = ret.get(propertyName);
                if (p != null && p.type.equals(valueType)) {
                    p.setMethod = m;
                }
            }
        }
    }
    // exclude incomplete get/set pair, and generate test value
    Iterator<Entry<String, GetSetPair>> itr = ret.entrySet().iterator();
    while (itr.hasNext()) {
        Entry<String, GetSetPair> cur = itr.next();
        GetSetPair gsp = cur.getValue();
        if ((gsp.getMethod == null) || (gsp.setMethod == null)) {
            LOG.info(String.format("Exclude protential property: %s\n", gsp.propertyName));
            itr.remove();
        } else {
            LOG.info(String.format("New property: %s type: %s", gsp.toString(), gsp.type));
            gsp.testValue = genTypeValue(gsp.type);
            LOG.info(String.format(" testValue: %s\n", gsp.testValue));
        }
    }
    return ret;
}

From source file:net.camelpe.extension.camel.typeconverter.CdiTypeConverterBuilder.java

private void ensureFallbackConverterMethodIsValid(final Class<?> type, final Method method)
        throws IllegalArgumentException {
    final Class<?>[] parameterTypes = method.getParameterTypes();
    final boolean hasCorrectParameters = (parameterTypes != null) && ((parameterTypes.length == 3)
            || (((parameterTypes.length == 4) && Exchange.class.isAssignableFrom(parameterTypes[1]))
                    && (TypeConverterRegistry.class
                            .isAssignableFrom(parameterTypes[parameterTypes.length - 1]))));
    if (!hasCorrectParameters) {
        throw new IllegalArgumentException(
                "Illegal fallback converter method [" + method + "] on type [" + type.getName()
                        + "]: a fallback converter method must have exactly three parameters, or it must have "
                        + "exactly four parameters. In both cases, the second parameter must be of type ["
                        + Exchange.class.getName() + "] and the last parameter must be of type ["
                        + TypeConverterRegistry.class.getName() + "].");
    }/*  w  w  w .ja  va 2 s  .  c o m*/

    final int modifiers = method.getModifiers();
    if (isAbstract(modifiers) || !isPublic(modifiers)) {
        throw new IllegalArgumentException(
                "Illegal fallback converter method [" + method + "] on type [" + type.getName()
                        + "]: a fallback converter method must not be abstract, and it must be public.");
    }

    final Class<?> toType = method.getReturnType();
    if (toType.equals(Void.class)) {
        throw new IllegalArgumentException("Illegal fallback converter method [" + method + "] on type ["
                + type.getName() + "]: a fallback converter method must not return void.");
    }
}

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

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

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

    VelocityContext context = new VelocityContext();

    context.put("priority", measurementQuality.getPriority());
    context.put("warmupTime", measurementQuality.getWarmupTime());
    context.put("warmupCycles", measurementQuality.getNumberOfWarmupCycles());
    context.put("measurementCycles", measurementQuality.getNumberOfMeasurementsCycles());
    context.put("measurementTime", measurementQuality.getMeasurementTime());

    String pathToMainDir = System.getProperty("user.dir");
    String pathToDir = pathToMainDir + File.separator
            + getDirectory().replaceAll("/", Matcher.quoteReplacement(File.separator)) + File.separator;
    context.put("directoryWhereToSaveResults", StringEscapeUtils.escapeJava(pathToDir));

    context.put("mClass", mrInfo.getContainingClass().getName());
    context.put("mFunctionIsStatic", Modifier.isStatic(testedMethod.getModifiers()));

    writeCode(context, templateMeasurementName);

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

    List<String> classPaths = getCompilationClassPaths();
    classPaths.add(javaClassDirectory);//  w w w .  j av  a  2  s . co  m

    Compiler.compile(javaSourceName, classPaths);
}

From source file:com.dpbymqn.fsm.manager.FsmManager.java

private TransitionCallback invokeTransitor(final Method m, StateListener sl) {
    final WeakReference<StateListener> slRef = new WeakReference<StateListener>(sl);
    final TransitionCallback cbk = new TransitionCallback() {
        @Override/*from w ww .  j  a v  a 2s. c om*/
        public void onTransition(StatefulObject st, String fromState, String toState) {
            if (m.getParameterTypes() != null) {
                // many different types and possibilities
                switch (m.getParameterTypes().length) {
                case 0:
                    invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get());
                    break;
                case 1:
                    if (String.class.equals(m.getParameterTypes()[0])) {
                        if (fromState != null) {
                            invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get(), toState);
                        } else {
                            invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get(), fromState);
                        }
                    } else if (StatefulObject.class.isAssignableFrom(m.getParameterTypes()[0])) {
                        invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get(), st);
                    } else {
                        //                                invoke(m, Modifier.isStatic(m.getModifiers()) ? null : sl, st);
                        throw new UnsupportedOperationException("Single parameter, but not recognized:"
                                + m.getParameterTypes()[0].getSimpleName());
                    }
                    break;
                case 2:
                    if (String.class.equals(m.getParameterTypes()[0])) {
                        invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get(), fromState, toState);
                    } else if (StatefulObject.class.isAssignableFrom(m.getParameterTypes()[0])) {
                        if (fromState != null) {
                            invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get(), st, toState);
                        } else {
                            invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get(), st, fromState);
                        }
                    }
                    break;
                case 3:
                    // format: void method( Stated st, String fromState, String toState )
                    invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get(), st, fromState, toState);
                    break;
                }
            }
        }
    };
    return cbk;
}

From source file:org.apache.axis.description.JavaServiceDesc.java

/**
 * Look for methods matching this name, and for each one, create an
 * OperationDesc (if it's not already in our list).
 *
 * TODO: Make this more efficient/*  w ww .  j a  v  a  2 s . c  o m*/
 */
private void createOperationsForName(Class implClass, String methodName) {
    // If we're a Skeleton deployment, skip the statics.
    if (isSkeletonClass) {
        if (methodName.equals("getOperationDescByName") || methodName.equals("getOperationDescs"))
            return;
    }

    Method[] methods = getMethods(implClass);

    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        if (Modifier.isPublic(method.getModifiers()) && method.getName().equals(methodName)
                && !isServiceLifeCycleMethod(implClass, method)) {
            createOperationForMethod(method);
        }
    }

    Class superClass = implClass.getSuperclass();
    if (superClass != null && !superClass.getName().startsWith("java.")
            && !superClass.getName().startsWith("javax.")
            && (stopClasses == null || !stopClasses.contains(superClass.getName()))) {
        createOperationsForName(superClass, methodName);
    }
}