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.pig.scripting.groovy.GroovyScriptEngine.java

@Override
protected Map<String, List<PigStats>> main(PigContext context, String scriptFile) throws IOException {

    PigServer pigServer = new PigServer(context, false);

    ///*from w  w  w. jav  a2  s  . c  o  m*/
    // Register dependencies
    //

    String groovyJar = getJarPath(groovy.util.GroovyScriptEngine.class);

    if (null != groovyJar) {
        pigServer.registerJar(groovyJar);
    }

    //
    // Register UDFs
    //

    registerFunctions(scriptFile, null, context);

    try {

        //
        // Load the script
        //

        Class c = gse.loadScriptByName(new File(scriptFile).toURI().toString());

        //
        // Extract the main method
        //

        Method main = c.getMethod("main", String[].class);

        if (null == main || !Modifier.isStatic(main.getModifiers()) || !Modifier.isPublic(main.getModifiers())
                || !Void.TYPE.equals(main.getReturnType())) {
            throw new IOException("No method 'public static void main(String[] args)' was found.");
        }

        //
        // Invoke the main method
        //

        Object[] args = new Object[1];
        String[] argv = (String[]) ObjectSerializer
                .deserialize(context.getProperties().getProperty(PigContext.PIG_CMD_ARGS_REMAINDERS));
        args[0] = argv;

        main.invoke(null, args);

    } catch (Exception e) {
        throw new IOException(e);
    }

    return getPigStatsMap();
}

From source file:edu.umich.flowfence.sandbox.ResolvedQM.java

private InstanceMethodData resolveInstance(Class<?> definingClass, String methodName, Class<?>[] paramClasses,
        boolean bestMatch) throws Exception {
    if (localLOGD) {
        Log.d(TAG, "Resolving as instance");
    }// w  w  w .java 2s.  c om
    final Method method = definingClass.getMethod(methodName, paramClasses);
    if (Modifier.isStatic(method.getModifiers())) {
        throw new NoSuchMethodException("Method is static, but was resolved as instance");
    }

    return new InstanceMethodData(method);
}

From source file:net.erdfelt.android.sdkfido.configer.Configer.java

private void findRawArgsMethod(Class<?> clazz) {
    for (Method method : clazz.getDeclaredMethods()) {
        ConfigArguments arg = method.getAnnotation(ConfigArguments.class);
        if (arg == null) {
            continue; // skip, not tagged
        }/* w ww.  java 2  s.  c  o  m*/

        int mods = method.getModifiers();
        if (!Modifier.isPublic(mods)) {
            continue; // skip, not public
        }

        if (Modifier.isStatic(mods)) {
            continue; // skip, dont support static
        }

        Class<?>[] params = method.getParameterTypes();
        if (params == null) {
            continue; // skip, needs params
        }

        if (params.length != 1) {
            continue; // skip, needs 1 param
        }

        if (!(params[0].equals(String.class))) {
            continue; // skip, param must be String
        }

        if (this.rawArgAdder != null) {
            StringBuilder err = new StringBuilder();
            err.append("Not allowed to have multiple @ConfigArguments defined: ");
            err.append("\n  Duplicate found at ").append(clazz.getName()).append("#").append(method.getName());
            err.append("\n  Original found at ").append(rawArgAdder.getDeclaringClass().getName()).append("#")
                    .append(rawArgAdder.getName());
            throw new IllegalStateException(err.toString());
        }

        this.rawArgAdder = method;
    }
}

From source file:edu.umich.flowfence.sandbox.ResolvedQM.java

private MethodData resolveStatic(Class<?> definingClass, String methodName, Class<?>[] paramClasses,
        boolean bestMatch) throws Exception {
    if (localLOGD) {
        Log.d(TAG, "Resolving as static");
    }//from   w w  w  .  ja  v  a  2  s. c o  m
    final Method method = definingClass.getMethod(methodName, paramClasses);
    if (!Modifier.isStatic(method.getModifiers())) {
        throw new NoSuchMethodException("Method is instance, but was resolved as static");
    }

    return new MethodData(method);
}

From source file:org.codehaus.griffon.commons.ClassPropertyFetcher.java

private void init() {
    FieldCallback fieldCallback = new ReflectionUtils.FieldCallback() {
        public void doWith(Field field) {
            if (field.isSynthetic())
                return;
            final int modifiers = field.getModifiers();
            if (!Modifier.isPublic(modifiers))
                return;

            final String name = field.getName();
            if (name.indexOf('$') == -1) {
                boolean staticField = Modifier.isStatic(modifiers);
                if (staticField) {
                    staticFetchers.put(name, new FieldReaderFetcher(field, staticField));
                } else {
                    instanceFetchers.put(name, new FieldReaderFetcher(field, staticField));
                }//ww  w. j a  v a2s .c  o  m
            }
        }
    };

    MethodCallback methodCallback = new ReflectionUtils.MethodCallback() {
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            if (method.isSynthetic())
                return;
            if (!Modifier.isPublic(method.getModifiers()))
                return;
            if (Modifier.isStatic(method.getModifiers()) && method.getReturnType() != Void.class) {
                if (method.getParameterTypes().length == 0) {
                    String name = method.getName();
                    if (name.indexOf('$') == -1) {
                        if (name.length() > 3 && name.startsWith("get")
                                && Character.isUpperCase(name.charAt(3))) {
                            name = name.substring(3);
                        } else if (name.length() > 2 && name.startsWith("is")
                                && Character.isUpperCase(name.charAt(2))
                                && (method.getReturnType() == Boolean.class
                                        || method.getReturnType() == boolean.class)) {
                            name = name.substring(2);
                        }
                        PropertyFetcher fetcher = new GetterPropertyFetcher(method, true);
                        staticFetchers.put(name, fetcher);
                        staticFetchers.put(StringUtils.uncapitalize(name), fetcher);
                    }
                }
            }
        }
    };

    List<Class<?>> allClasses = resolveAllClasses(clazz);
    for (Class<?> c : allClasses) {
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            try {
                fieldCallback.doWith(field);
            } catch (IllegalAccessException ex) {
                throw new IllegalStateException(
                        "Shouldn't be illegal to access field '" + field.getName() + "': " + ex);
            }
        }
        Method[] methods = c.getDeclaredMethods();
        for (Method method : methods) {
            try {
                methodCallback.doWith(method);
            } catch (IllegalAccessException ex) {
                throw new IllegalStateException(
                        "Shouldn't be illegal to access method '" + method.getName() + "': " + ex);
            }
        }
    }

    propertyDescriptors = BeanUtils.getPropertyDescriptors(clazz);
    for (PropertyDescriptor desc : propertyDescriptors) {
        Method readMethod = desc.getReadMethod();
        if (readMethod != null) {
            boolean staticReadMethod = Modifier.isStatic(readMethod.getModifiers());
            if (staticReadMethod) {
                staticFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod));
            } else {
                instanceFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod));
            }
        }
    }
}

From source file:org.jboss.dashboard.ui.config.components.factory.FactoryComponentFormatter.java

protected boolean isGetter(Method m) {
    if (m.getParameterTypes().length > 0)
        return false;
    Class returnType = m.getReturnType();
    if (returnType == null || returnType.equals(void.class))
        return false;
    int modifiers = m.getModifiers();
    if (!Modifier.isPublic(modifiers)) {
        return false;
    }/* w  ww.j  a  v a  2  s  .c o m*/
    if (m.getName().startsWith("get") && !"get".equals(m.getName()) && !"getClass".equals(m.getName())) {
        return true;
    }
    if (m.getName().startsWith("is") && !"is".equals(m.getName()) && boolean.class.equals(returnType)) {
        return true;
    }
    return false;
}

From source file:org.ajax4jsf.builder.config.ComponentBaseBean.java

/**
 * Subclasses should extend this method to provide specifc checks
 * /*from   ww w .j a v  a  2 s .co m*/
 * Check existing and default properties
 * For properties filled from configuration, attempt to set additional parameters.
 * If base class have any bean properties, append it to configured
 * @throws ConfigurationException 
 */
public void checkProperties() throws ParsingException {
    try {
        getLog().debug("Parse properties for Component " + getName() + " with superclass " + getSuperclass());
        if (getSuperclass() != null) {
            Class<?> superClass = getLoader().loadClass(getSuperclass());

            new ClassWalkingLogic(superClass).walk(new ClassVisitor() {
                public void visit(Class<?> clazz) {
                    checkPropertiesForClass(clazz);
                }
            });
        }
    } catch (ClassNotFoundException e) {
        getLog().error("superclass not found for component " + getName(), e);
    }
    if (null != getTag()) {
        try {
            Class superClass = getLoader().loadClass(getTag().getSuperclass());
            PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(superClass);
            // for all properties, add it to component. If property have not abstract getter/setter ,
            // add it with exist = true . If property in list of hidden names, set hidden = true.
            for (int i = 0; i < properties.length; i++) {
                PropertyDescriptor descriptor = properties[i];
                Method writeMethod = descriptor.getWriteMethod();
                if (containProperty(descriptor.getName())) {
                    if (null != writeMethod && !Modifier.isAbstract(writeMethod.getModifiers())
                            && Modifier.isPublic(writeMethod.getModifiers())) {
                        ((PropertyBean) this.properties.get(descriptor.getName())).setExistintag(true);
                    }
                } else if (null != writeMethod && Modifier.isPublic(writeMethod.getModifiers())) {
                    if (Arrays.asList(enabledTagProperties).contains(descriptor.getName())) {
                        Class type = descriptor.getPropertyType();
                        getLog().debug("Register tag property  " + descriptor.getName() + " with type name "
                                + type.getCanonicalName());
                        PropertyBean property = new PropertyBean();
                        property.setName(descriptor.getName());
                        property.setDescription(descriptor.getShortDescription());
                        property.setDisplayname(descriptor.getDisplayName());
                        property.setClassname(descriptor.getPropertyType().getCanonicalName());
                        property.setExist(true);
                        if (!Modifier.isAbstract(writeMethod.getModifiers())) {
                            property.setExistintag(true);
                        }
                        addProperty(property);
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            getLog().error("superclass not found for tag " + getTag().getName(), e);
        }

    }
}

From source file:org.grails.datastore.mapping.reflect.ClassPropertyFetcher.java

private void init() {

    List<Class> allClasses = resolveAllClasses(clazz);
    for (Class c : allClasses) {
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            processField(field);//from  w  w w  .  j a  va  2 s.c o  m
        }
        Method[] methods = c.getDeclaredMethods();
        for (Method method : methods) {
            processMethod(method);
        }
    }

    try {
        propertyDescriptors = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
    } catch (IntrospectionException e) {
        // ignore
    }

    if (propertyDescriptors == null) {
        return;
    }

    for (PropertyDescriptor desc : propertyDescriptors) {
        propertyDescriptorsByName.put(desc.getName(), desc);
        final Class<?> propertyType = desc.getPropertyType();
        if (propertyType == null)
            continue;
        List<PropertyDescriptor> pds = typeToPropertyMap.get(propertyType);
        if (pds == null) {
            pds = new ArrayList<PropertyDescriptor>();
            typeToPropertyMap.put(propertyType, pds);
        }
        pds.add(desc);

        Method readMethod = desc.getReadMethod();
        if (readMethod != null) {
            boolean staticReadMethod = Modifier.isStatic(readMethod.getModifiers());
            if (staticReadMethod) {
                List<PropertyFetcher> propertyFetchers = staticFetchers.get(desc.getName());
                if (propertyFetchers == null) {
                    staticFetchers.put(desc.getName(), propertyFetchers = new ArrayList<PropertyFetcher>());
                }
                propertyFetchers.add(new GetterPropertyFetcher(readMethod, true));
            } else {
                instanceFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, false));
            }
        }
    }
}

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

/**
 * Check the method for the required properties (public, static, params:(String[])).
 *
 * @param method the method/*w w  w . j  a v  a2  s  .  c  om*/
 * @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;
}

From source file:com.datos.vfs.util.DelegatingFileSystemOptionsBuilder.java

/**
 * tries to convert the value and pass it to the given method
 */// w  w w. j av a  2  s.c om
private boolean convertValuesAndInvoke(final Method configSetter, final Context ctx)
        throws FileSystemException {
    final Class<?>[] parameters = configSetter.getParameterTypes();
    if (parameters.length < 2) {
        return false;
    }
    if (!parameters[0].isAssignableFrom(FileSystemOptions.class)) {
        return false;
    }

    final Class<?> valueParameter = parameters[1];
    Class<?> type;
    if (valueParameter.isArray()) {
        type = valueParameter.getComponentType();
    } else {
        if (ctx.values.length > 1) {
            return false;
        }

        type = valueParameter;
    }

    if (type.isPrimitive()) {
        final Class<?> objectType = PRIMATIVE_TO_OBJECT.get(type.getName());
        if (objectType == null) {
            log.warn(Messages.getString("vfs.provider/config-unexpected-primitive.error", type.getName()));
            return false;
        }
        type = objectType;
    }

    final Class<? extends Object> valueClass = ctx.values[0].getClass();
    if (type.isAssignableFrom(valueClass)) {
        // can set value directly
        invokeSetter(valueParameter, ctx, configSetter, ctx.values);
        return true;
    }
    if (valueClass != String.class) {
        log.warn(Messages.getString("vfs.provider/config-unexpected-value-class.error", valueClass.getName(),
                ctx.scheme, ctx.name));
        return false;
    }

    final Object convertedValues = Array.newInstance(type, ctx.values.length);

    Constructor<?> valueConstructor;
    try {
        valueConstructor = type.getConstructor(STRING_PARAM);
    } catch (final NoSuchMethodException e) {
        valueConstructor = null;
    }
    if (valueConstructor != null) {
        // can convert using constructor
        for (int iterValues = 0; iterValues < ctx.values.length; iterValues++) {
            try {
                Array.set(convertedValues, iterValues,
                        valueConstructor.newInstance(new Object[] { ctx.values[iterValues] }));
            } catch (final InstantiationException e) {
                throw new FileSystemException(e);
            } catch (final IllegalAccessException e) {
                throw new FileSystemException(e);
            } catch (final InvocationTargetException e) {
                throw new FileSystemException(e);
            }
        }

        invokeSetter(valueParameter, ctx, configSetter, convertedValues);
        return true;
    }

    Method valueFactory;
    try {
        valueFactory = type.getMethod("valueOf", STRING_PARAM);
        if (!Modifier.isStatic(valueFactory.getModifiers())) {
            valueFactory = null;
        }
    } catch (final NoSuchMethodException e) {
        valueFactory = null;
    }

    if (valueFactory != null) {
        // can convert using factory method (valueOf)
        for (int iterValues = 0; iterValues < ctx.values.length; iterValues++) {
            try {
                Array.set(convertedValues, iterValues,
                        valueFactory.invoke(null, new Object[] { ctx.values[iterValues] }));
            } catch (final IllegalAccessException e) {
                throw new FileSystemException(e);
            } catch (final InvocationTargetException e) {
                throw new FileSystemException(e);
            }
        }

        invokeSetter(valueParameter, ctx, configSetter, convertedValues);
        return true;
    }

    return false;
}