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:com.appleframework.jmx.connector.framework.ConnectorRegistry.java

@SuppressWarnings("deprecation")
private static ConnectorRegistry create(ApplicationConfig config) throws Exception {

    Map<String, String> paramValues = config.getParamValues();
    String appId = config.getApplicationId();
    String connectorId = (String) paramValues.get("connectorId");

    File file1 = new File(CoreUtils.getConnectorDir() + File.separatorChar + connectorId);

    URL[] urls = new URL[] { file1.toURL() };
    ClassLoader cl = ClassLoaderRepository.getClassLoader(urls, true);

    //URLClassLoader cl = new URLClassLoader(urls,
    //        ConnectorMBeanRegistry.class.getClassLoader());

    Registry.MODELER_MANIFEST = MBEANS_DESCRIPTOR;
    URL res = cl.getResource(MBEANS_DESCRIPTOR);

    logger.info("Application ID   : " + appId);
    logger.info("Connector Archive: " + file1.getAbsoluteFile());
    logger.info("MBean Descriptor : " + res.toString());

    //Thread.currentThread().setContextClassLoader(cl);
    //Registry.setUseContextClassLoader(true);

    ConnectorRegistry registry = new ConnectorRegistry();
    registry.loadMetadata(cl);//ww w . ja  v  a2 s.com

    String[] mbeans = registry.findManagedBeans();

    MBeanServer server = MBeanServerFactory.newMBeanServer(DOMAIN_CONNECTOR);

    for (int i = 0; i < mbeans.length; i++) {
        ManagedBean managed = registry.findManagedBean(mbeans[i]);
        String clsName = managed.getType();
        String domain = managed.getDomain();
        if (domain == null) {
            domain = DOMAIN_CONNECTOR;
        }

        Class<?> cls = Class.forName(clsName, true, cl);
        Object objMBean = null;

        // Use the factory method when it is defined.
        Method[] methods = cls.getMethods();
        for (Method method : methods) {
            if (method.getName().equals(FACTORY_METHOD) && Modifier.isStatic(method.getModifiers())) {
                objMBean = method.invoke(null);
                logger.info("Create MBean using factory method.");
                break;
            }
        }

        if (objMBean == null) {
            objMBean = cls.newInstance();
        }

        // Call the initialize method if the MBean extends ConnectorSupport class
        if (objMBean instanceof ConnectorSupport) {
            Method method = cls.getMethod("initialize", new Class[] { Map.class });
            Map<String, String> props = config.getParamValues();
            method.invoke(objMBean, new Object[] { props });
        }
        ModelMBean mm = managed.createMBean(objMBean);

        String beanObjName = domain + ":name=" + mbeans[i];
        server.registerMBean(mm, new ObjectName(beanObjName));
    }

    registry.setMBeanServer(server);
    entries.put(appId, registry);
    return registry;
}

From source file:org.geoserver.catalog.impl.ModificationProxyCloner.java

/**
 * Best effort object cloning utility, tries different lightweight strategies, then falls back
 * on copy by XStream serialization (we use that one as we have a number of hooks to avoid deep
 * copying the catalog, and re-attaching to it, in there)
 * /*from ww w  . ja va 2s . c o m*/
 * @param source
 * @return
 */
static <T> T clone(T source) {
    // null?
    if (source == null) {
        return null;
    }

    // already a modification proxy?
    if (ModificationProxy.handler(source) != null) {
        return source;
    }

    // is it a catalog info?
    if (source instanceof CatalogInfo) {
        // mumble... shouldn't we wrap this one in a modification proxy object?
        return (T) ModificationProxy.create(source, getDeepestCatalogInfoInterface((CatalogInfo) source));
    }

    // if a known immutable?
    if (source instanceof String || source instanceof Byte || source instanceof Short
            || source instanceof Integer || source instanceof Float || source instanceof Double
            || source instanceof BigInteger || source instanceof BigDecimal) {
        return (T) source;
    }

    // is it cloneable?
    try {
        if (source instanceof Cloneable) {
            // methodutils does not seem to work against "clone()"...
            // return (T) MethodUtils.invokeExactMethod(source, "clone", null, null);
            Method method = source.getClass().getDeclaredMethod("clone");
            if (Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0) {
                return (T) method.invoke(source);
            }
        }
    } catch (Exception e) {
        LOGGER.log(Level.FINE,
                "Source object is cloneable, yet it does not have a public no argument method 'clone'", e);
    }

    // does it have a copy constructor?
    Constructor copyConstructor = ConstructorUtils.getAccessibleConstructor(source.getClass(),
            source.getClass());
    if (copyConstructor != null) {
        try {
            return (T) copyConstructor.newInstance(source);
        } catch (Exception e) {
            LOGGER.log(Level.FINE, "Source has a copy constructor, but it failed, skipping to XStream", e);
        }
    }

    if (source instanceof Serializable) {
        return (T) SerializationUtils.clone((Serializable) source);
    } else {
        XStreamPersister persister = XSTREAM_PERSISTER_FACTORY.createXMLPersister();
        XStream xs = persister.getXStream();
        String xml = xs.toXML(source);
        T copy = (T) xs.fromXML(xml);
        return copy;
    }
}

From source file:com.wrmsr.search.dsl.util.DerivedSuppliers.java

public static <T> Class<? extends Supplier<T>> compile(java.lang.reflect.Method target,
        ClassLoader parentClassLoader) throws ReflectiveOperationException {
    checkArgument((target.getModifiers() & STATIC.getModifier()) > 0);
    List<TargetParameter> targetParameters = IntStream.range(0, target.getParameterCount()).boxed()
            .map(i -> new TargetParameter(target, i)).collect(toImmutableList());

    java.lang.reflect.Type targetReturnType = target.getGenericReturnType();
    java.lang.reflect.Type suppliedType = boxType(targetReturnType);
    checkArgument(suppliedType instanceof Class);

    ClassDefinition classDefinition = new ClassDefinition(a(PUBLIC, FINAL),
            CompilerUtils.makeClassName(
                    "DerivedSupplier__" + target.getDeclaringClass().getName() + "__" + target.getName()),
            type(Object.class), type(Supplier.class, fromReflectType(suppliedType)));

    targetParameters.forEach(p -> classDefinition.addField(a(PRIVATE, FINAL), p.name,
            type(Supplier.class, p.parameterizedBoxedType)));
    Map<String, FieldDefinition> classFieldDefinitionMap = classDefinition.getFields().stream()
            .collect(toImmutableMap(f -> f.getName(), f -> f));

    compileConstructor(classDefinition, classFieldDefinitionMap, targetParameters);
    compileGetter(classDefinition, classFieldDefinitionMap, target, targetParameters);

    Class clazz = defineClass(classDefinition, Object.class, ImmutableMap.of(),
            new DynamicClassLoader(parentClassLoader));
    return clazz;
}

From source file:com.github.juanmf.java2plant.Parser.java

protected static void addUses(Set<Relation> relations, Class<?> fromType) {
    Method[] methods = fromType.getDeclaredMethods();
    for (Method m : methods) {
        if (!Modifier.isPrivate(m.getModifiers())) {
            addMethodUses(relations, fromType, m);
        }/*from www .j  a v a 2s.c o  m*/
    }
    Constructor<?>[] constructors = fromType.getDeclaredConstructors();
    for (Constructor<?> c : constructors) {
        if (!Modifier.isPrivate(c.getModifiers())) {
            addConstructorUses(relations, fromType, c);
        }
    }
}

From source file:com.palantir.ptoss.util.Reflections.java

/**
 * Returns whether or not the given {@link Method} is public.
 *//* w w  w.j  a  v a2 s.com*/
public static boolean isMethodPublic(Method method) {
    int modifiers = method.getModifiers();
    return Modifier.isPublic(modifiers);
}

From source file:org.evosuite.setup.TestClusterUtils.java

public static boolean hasStaticGenerator(Class<?> clazz) {
    for (Method m : ReflectionUtils.getMethods(clazz)) {
        if (Modifier.isStatic(m.getModifiers())) {
            if (clazz.isAssignableFrom(m.getReturnType())) {
                return true;
            }//from w w w .  j  a va2 s.c  om
        }
    }
    return false;
}

From source file:net.abhinavsarkar.spelhelper.SpelHelper.java

private static List<Method> filterMethods(final Class<?> clazz) {
    List<Method> allowedMethods = new ArrayList<Method>();
    for (Method method : clazz.getMethods()) {
        int modifiers = method.getModifiers();
        if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)
                && !method.getReturnType().equals(Void.TYPE) && method.getParameterTypes().length > 0) {
            allowedMethods.add(method);/* ww w  . ja va  2 s . c o m*/
        }
    }
    return allowedMethods;
}

From source file:net.abhinavsarkar.spelhelper.SpelHelper.java

private static List<Method> filterFunctions(final Class<?> clazz) {
    List<Method> allowedMethods = new ArrayList<Method>();
    for (Method method : clazz.getMethods()) {
        int modifiers = method.getModifiers();
        if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)
                && !method.getReturnType().equals(Void.TYPE)) {
            allowedMethods.add(method);/*from   w w  w .  ja  va 2s .c o  m*/
        }
    }
    return allowedMethods;
}

From source file:org.eclipse.gemini.blueprint.compendium.internal.cm.UpdateMethodAdapter.java

/**
 * Determines the update method./*  www .  j a  va2s  .co  m*/
 * 
 * @param target
 * @param methodName
 * @return
 */
static Map determineUpdateMethod(final Class<?> target, final String methodName) {
    Assert.notNull(target);
    Assert.notNull(methodName);

    final Map methods = new LinkedHashMap(2);
    final boolean trace = log.isTraceEnabled();

    org.springframework.util.ReflectionUtils.doWithMethods(target,
            new org.springframework.util.ReflectionUtils.MethodCallback() {

                public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                    // consider filtering bridge non-void and non-public methods as well
                    if (!method.isBridge() && Modifier.isPublic(method.getModifiers())
                            && (void.class.equals(method.getReturnType()))
                            && methodName.equals(method.getName())) {
                        // check the argument types
                        Class<?>[] args = method.getParameterTypes();

                        // Properties can be passed as Map or Dictionary
                        if (args != null && args.length == 1) {
                            Class<?> propertiesType = args[0];
                            if (propertiesType.isAssignableFrom(Map.class)
                                    || propertiesType.isAssignableFrom(Dictionary.class)) {

                                if (trace)
                                    log.trace("Discovered custom method [" + method.toString() + "] on "
                                            + target);
                                // see if there was a method already found
                                Method m = (Method) methods.get(propertiesType);

                                if (m != null) {
                                    if (trace)
                                        log.trace(
                                                "Type " + propertiesType + " already has an associated method ["
                                                        + m.toString() + "];ignoring " + method);
                                } else
                                    methods.put(propertiesType, method);
                            }
                        }
                    }
                }
            });

    return methods;
}

From source file:org.jfree.data.KeyToGroupMap.java

/**
 * Attempts to clone the specified object using reflection.
 *
 * @param object  the object (<code>null</code> permitted).
 *
 * @return The cloned object, or the original object if cloning failed.
 *//*from   w  ww  .  j  av a  2 s.co  m*/
private static Object clone(Object object) {
    if (object == null) {
        return null;
    }
    Class c = object.getClass();
    Object result = null;
    try {
        Method m = c.getMethod("clone", (Class[]) null);
        if (Modifier.isPublic(m.getModifiers())) {
            try {
                result = m.invoke(object, (Object[]) null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } catch (NoSuchMethodException e) {
        result = object;
    }
    return result;
}