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.baasbox.configuration.PropertiesConfigurationHelper.java

public static String dumpConfiguration(String section) {
    Class en = CONFIGURATION_SECTIONS.get(section);
    try {//  w ww.j  a  v  a  2s.co m
        StringBuilder sb = new StringBuilder();
        String enumDescription = "";

        Method getEnumDescription = en.getMethod("getEnumDescription");
        if (getEnumDescription != null && getEnumDescription.getReturnType() == String.class
                && Modifier.isStatic(getEnumDescription.getModifiers()))
            enumDescription = (String) getEnumDescription.invoke(null);

        sb.append(enumDescription);
        sb.append("\n");
        sb.append(section.toUpperCase());
        sb.append("\n");

        String lastSection = "";
        EnumSet values = EnumSet.allOf(en);
        for (Object v : values) {
            String key = (String) ((Method) v.getClass().getMethod("getKey")).invoke(v);
            Object value = ((Method) en.getMethod("getValue")).invoke(v);
            String subsection = key.substring(0, key.indexOf('.'));

            if (!lastSection.equals(subsection)) {
                sb.append("  - ");
                sb.append(subsection.toUpperCase());
                sb.append("\n");
                lastSection = subsection;
            }
            sb.append("      + ");
            sb.append(key);
            sb.append(" = ");
            sb.append(value);
            sb.append("\n");
        }
        return sb.toString();
    } catch (Exception e) {
        BaasBoxLogger.error("Cannot generate a json for " + en.getSimpleName()
                + " Enum. Is it an Enum that implements the IProperties interface?", e);
    }
    return "";
}

From source file:de.pribluda.android.jsonmarshaller.JSONMarshaller.java

/**
 * recursively marshall to JSON//ww w.j a v  a 2 s.  c o  m
 *
 * @param sink
 * @param object
 */
static void marshallRecursive(JSONObject sink, Object object)
        throws JSONException, InvocationTargetException, IllegalAccessException, NoSuchMethodException {
    // nothing to marshall
    if (object == null)
        return;
    // primitive object is a field and does not interes us here
    if (object.getClass().isPrimitive())
        return;
    // object not null,  and is not primitive - iterate through getters
    for (Method method : object.getClass().getMethods()) {
        // our getters are parameterless and start with "get"
        if ((method.getName().startsWith(GETTER_PREFIX) && method.getName().length() > BEGIN_INDEX
                || method.getName().startsWith(IS_PREFIX) && method.getName().length() > IS_LENGTH)
                && (method.getModifiers() & Modifier.PUBLIC) != 0 && method.getParameterTypes().length == 0
                && method.getReturnType() != void.class) {
            // is return value primitive?
            Class<?> type = method.getReturnType();
            if (type.isPrimitive() || String.class.equals(type)) {
                // it is, marshall it
                Object val = method.invoke(object);
                if (val != null) {
                    sink.put(propertize(method.getName()), val);
                }
                continue;
            } else if (type.isArray()) {
                Object val = marshallArray(method.invoke(object));
                if (val != null) {
                    sink.put(propertize(method.getName()), val);
                }
                continue;
            } else if (type.isAssignableFrom(Date.class)) {
                Date date = (Date) method.invoke(object);
                if (date != null) {
                    sink.put(propertize(method.getName()), date.getTime());
                }
                continue;
            } else if (type.isAssignableFrom(Boolean.class)) {
                Boolean b = (Boolean) method.invoke(object);
                if (b != null) {
                    sink.put(propertize(method.getName()), b.booleanValue());
                }
                continue;
            } else if (type.isAssignableFrom(Integer.class)) {
                Integer i = (Integer) method.invoke(object);
                if (i != null) {
                    sink.put(propertize(method.getName()), i.intValue());
                }
                continue;
            } else if (type.isAssignableFrom(Long.class)) {
                Long l = (Long) method.invoke(object);
                if (l != null) {
                    sink.put(propertize(method.getName()), l.longValue());
                }
                continue;
            } else {
                // does it have default constructor?
                try {
                    if (method.getReturnType().getConstructor() != null) {
                        Object val = marshall(method.invoke(object));
                        if (val != null) {
                            sink.put(propertize(method.getName()), val);
                        }
                        continue;
                    }
                } catch (NoSuchMethodException ex) {
                    // just ignore it here, it means no such constructor was found
                }
            }
        }
    }
}

From source file:ReflectUtil.java

/**
 * <p>Attempts to find an accessible version of the method passed in, where accessible
 * is defined as the method itself being public and the declaring class being public.
 * Mostly useful as a workaround to the situation when
 * {@link PropertyDescriptor#getReadMethod()} and/or
 * {@link java.beans.PropertyDescriptor#getWriteMethod()} returns methods that are not
 * accessible (usually due to public implementations of interface methods in private
 * classes).</p>//w  w w . ja  va 2 s .c o  m
 *
 * <p>Checks the method passed in and if it already meets these criteria it is returned
 * immediately. In general this leads to very little performance overhead</p>
 *
 * <p>If the method does not meet the criteria then the class' interfaces are scanned
 * for a matching method. If one is not found, then the class' superclass hierarchy
 * is searched. Finally, if no matching method can be found the original method is
 * returned.</p>
 *
 * @param m a method that may or may not be accessible
 * @return either an accessible version of the same method, or the method passed in if
 *         an accessible version cannot be found
 */
public static Method findAccessibleMethod(final Method m) {
    // If the passed in method is accessible, then just give it back.
    if (isPublic(m.getModifiers()) && isPublic(m.getDeclaringClass().getModifiers()))
        return m;
    if (m.isAccessible())
        return m;

    final Class<?> clazz = m.getDeclaringClass();
    final String name = m.getName();
    final Class<?>[] ptypes = m.getParameterTypes();

    // Else, loop through the interfaces for the declaring class, looking for a
    // public version of the method that we can call
    for (Class<?> iface : clazz.getInterfaces()) {
        try {
            Method m2 = iface.getMethod(name, ptypes);
            if (m2.isAccessible())
                return m2;
            if (isPublic(iface.getModifiers()) && isPublic(m2.getModifiers()))
                return m2;
        } catch (NoSuchMethodException nsme) {
            /* Not Unexpected. */ }
    }

    // Else loop through the superclasses looking for a public method
    Class<?> c = clazz.getSuperclass();
    while (c != null) {
        try {
            Method m2 = c.getMethod(name, ptypes);
            if (m2.isAccessible())
                return m2;
            if (isPublic(c.getModifiers()) && isPublic(m2.getModifiers()))
                return m2;
        } catch (NoSuchMethodException nsme) {
            /* Not Unexpected. */ }

        c = c.getSuperclass();
    }

    // If we haven't found anything at this point, just give up!
    return m;
}

From source file:HashNMap.java

/**
 * Returns a clone of the specified object, if it can be cloned, otherwise
 * throws a CloneNotSupportedException./*  w  ww  .  j a va  2 s .  c o m*/
 * 
 * @param object
 *          the object to clone (<code>null</code> not permitted).
 * @return A clone of the specified object.
 * @throws CloneNotSupportedException
 *           if the object cannot be cloned.
 */
public static Object clone(final Object object) throws CloneNotSupportedException {
    if (object == null) {
        throw new IllegalArgumentException("Null 'object' argument.");
    }

    else {
        try {
            final Method method = object.getClass().getMethod("clone", (Class[]) null);
            if (Modifier.isPublic(method.getModifiers())) {
                return method.invoke(object, (Object[]) null);
            }
        } catch (Exception e) {

        }
    }
    throw new CloneNotSupportedException("Failed to clone.");
}

From source file:org.jgentleframework.utils.control.Delegator.java

/**
 * utility code to find the one suitable method in the passed in interface.
 * //  w ww  .  j ava  2  s.  c om
 * @param TheInterface
 *            the the interface
 * @return the method
 */
protected static Method findMethod(Class TheInterface) {

    if (!TheInterface.isInterface())
        throw new IllegalArgumentException("DelegateTemplate must be constructed with an interface");
    Method[] methods = TheInterface.getMethods();
    Method ret = null;
    for (int i = 0; i < methods.length; i++) {
        Method test = methods[i];
        if (Modifier.isAbstract(test.getModifiers())) {
            if (ret != null)
                throw new IllegalArgumentException("DelegateTemplate must be constructed "
                        + " with an interface implementing only one method!");
            ret = test;
        }
    }
    if (ret == null)
        throw new IllegalArgumentException(
                "DelegateTemplate must be constructed " + " with an interface implementing exactly method!");
    return (ret);
}

From source file:com.baasbox.configuration.PropertiesConfigurationHelper.java

/***
 *
 * Returns a json representation of the Enumerator
 * The Enumerator must implements the IProperties interface
 * @param en    the Enumerator to serialize. It must implements the IProperties interface
 * @return       the representation of the Enumerator 
 *//*from   w w  w. j  av  a2  s.  co  m*/
@SuppressWarnings("unchecked")
public static String dumpConfigurationAsJson(String section) {
    Class en = CONFIGURATION_SECTIONS.get(section);
    try {
        JsonFactory jfactory = new JsonFactory();
        StringWriter sw = new StringWriter();
        String enumDescription = "";
        JsonGenerator gen = jfactory.createJsonGenerator(sw);

        Method getEnumDescription = en.getMethod("getEnumDescription");
        if (getEnumDescription != null && getEnumDescription.getReturnType() == String.class
                && Modifier.isStatic(getEnumDescription.getModifiers()))
            enumDescription = (String) getEnumDescription.invoke(null);
        gen.writeStartObject(); //{
        gen.writeStringField("section", section); //    "configuration":"EnumName"
        gen.writeStringField("description", enumDescription); //   ,"description": "EnumDescription"
        gen.writeFieldName("sub sections"); //  ,"sections":
        gen.writeStartObject(); //      {
        String lastSection = "";
        EnumSet values = EnumSet.allOf(en);
        for (Object v : values) {
            String key = (String) (en.getMethod("getKey")).invoke(v);
            boolean isVisible = (Boolean) (en.getMethod("isVisible")).invoke(v);
            String valueAsString;
            if (isVisible)
                valueAsString = (String) (en.getMethod("getValueAsString")).invoke(v);
            else
                valueAsString = "--HIDDEN--";
            boolean isEditable = (Boolean) (en.getMethod("isEditable")).invoke(v);
            String valueDescription = (String) (en.getMethod("getValueDescription")).invoke(v);
            Class type = (Class) en.getMethod("getType").invoke(v);
            String subsection = key.substring(0, key.indexOf('.'));
            if (!lastSection.equals(subsection)) {
                if (gen.getOutputContext().inArray())
                    gen.writeEndArray();
                gen.writeFieldName(subsection); //         "sectionName":
                gen.writeStartArray(); //            [
                lastSection = subsection;
            }
            boolean isOverridden = (Boolean) (en.getMethod("isOverridden")).invoke(v);
            gen.writeStartObject(); //               {
            gen.writeStringField(key, valueAsString); //                     "key": "value"   
            gen.writeStringField("description", valueDescription); //                  ,"description":"description"
            gen.writeStringField("type", type.getSimpleName()); //                  ,"type":"type"
            gen.writeBooleanField("editable", isEditable); //                  ,"editable":"true|false"
            gen.writeBooleanField("visible", isVisible); //                  ,"visible":"true|false"
            gen.writeBooleanField("overridden", isOverridden); //                  ,"overridden":"true|false"
            gen.writeEndObject(); //               }
        }
        if (gen.getOutputContext().inArray())
            gen.writeEndArray(); //            ]
        gen.writeEndObject(); //      }
        gen.writeEndObject(); //}
        gen.close();
        return sw.toString();
    } catch (Exception e) {
        BaasBoxLogger.error("Cannot generate a json for " + en.getSimpleName()
                + " Enum. Is it an Enum that implements the IProperties interface?", e);
    }
    return "{}";
}

From source file:com.ocs.dynamo.utils.ClassUtils.java

/**
 * Check if the object has a (public) method that has the specified name
 * // w w w.  j av  a  2  s  . c o  m
 * @param obj
 * @param methodName
 * @return
 */
public static boolean hasMethod(Object obj, String methodName) {
    Method[] methods = obj.getClass().getMethods();
    for (Method method : methods) {
        if (method.getName().equals(methodName) && (Modifier.isPublic(method.getModifiers()))) {
            return true;
        }
    }
    return false;
}

From source file:org.eiichiro.bootleg.Types.java

/**
 * Returns <code>true</code> if the specified type is an user define value 
 * type.//from   ww w.  ja v a2s  . co m
 * User defined value type must satisfy either of the following condition.
 * <ol>
 * <li>(The class) has a public constructor that takes one String.class parameter.</li>
 * <li>Has a public static factory method that named 'valueOf' and takes one 
 * String.class parameter.</li>
 * </ol>
 * 
 * @param type The type to be tested.
 * @return <code>true</code> if the specified type is an user define value 
 * type.
 */
public static boolean isUserDefinedValueType(Type type) {
    Class<?> rawType = getRawType(type);

    if (rawType == null) {
        return false;
    }

    for (Constructor<?> constructor : rawType.getConstructors()) {
        Class<?>[] parameterTypes = constructor.getParameterTypes();

        if (parameterTypes.length == 1 && parameterTypes[0].equals(String.class)) {
            return true;
        }
    }

    for (Method method : rawType.getMethods()) {
        if (method.getName().equals("valueOf") && Modifier.isStatic(method.getModifiers())) {
            return true;
        }
    }

    return false;
}

From source file:com.weibo.api.motan.config.springsupport.MotanBeanDefinitionParser.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static BeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass,
        boolean required) throws ClassNotFoundException {
    RootBeanDefinition bd = new RootBeanDefinition();
    bd.setBeanClass(beanClass);//from  w w w.  java  2s .c o m
    // ??lazy init
    bd.setLazyInit(false);

    // id?id,idcontext
    String id = element.getAttribute("id");
    if ((id == null || id.length() == 0) && required) {
        String generatedBeanName = element.getAttribute("name");
        if (generatedBeanName == null || generatedBeanName.length() == 0) {
            generatedBeanName = element.getAttribute("class");
        }
        if (generatedBeanName == null || generatedBeanName.length() == 0) {
            generatedBeanName = beanClass.getName();
        }
        id = generatedBeanName;
        int counter = 2;
        while (parserContext.getRegistry().containsBeanDefinition(id)) {
            id = generatedBeanName + (counter++);
        }
    }
    if (id != null && id.length() > 0) {
        if (parserContext.getRegistry().containsBeanDefinition(id)) {
            throw new IllegalStateException("Duplicate spring bean id " + id);
        }
        parserContext.getRegistry().registerBeanDefinition(id, bd);
    }
    bd.getPropertyValues().addPropertyValue("id", id);
    if (ProtocolConfig.class.equals(beanClass)) {
        MotanNamespaceHandler.protocolDefineNames.add(id);

    } else if (RegistryConfig.class.equals(beanClass)) {
        MotanNamespaceHandler.registryDefineNames.add(id);

    } else if (BasicServiceInterfaceConfig.class.equals(beanClass)) {
        MotanNamespaceHandler.basicServiceConfigDefineNames.add(id);

    } else if (BasicRefererInterfaceConfig.class.equals(beanClass)) {
        MotanNamespaceHandler.basicRefererConfigDefineNames.add(id);

    } else if (ServiceConfigBean.class.equals(beanClass)) {
        String className = element.getAttribute("class");
        if (className != null && className.length() > 0) {
            RootBeanDefinition classDefinition = new RootBeanDefinition();
            classDefinition.setBeanClass(
                    Class.forName(className, true, Thread.currentThread().getContextClassLoader()));
            classDefinition.setLazyInit(false);
            parseProperties(element.getChildNodes(), classDefinition);
            bd.getPropertyValues().addPropertyValue("ref",
                    new BeanDefinitionHolder(classDefinition, id + "Impl"));
        }
    }

    Set<String> props = new HashSet<String>();
    ManagedMap parameters = null;
    // ??setbd
    for (Method setter : beanClass.getMethods()) {
        String name = setter.getName();
        // setXXX
        if (name.length() <= 3 || !name.startsWith("set") || !Modifier.isPublic(setter.getModifiers())
                || setter.getParameterTypes().length != 1) {
            continue;
        }
        String property = (name.substring(3, 4).toLowerCase() + name.substring(4)).replaceAll("_", "-");
        props.add(property);
        if ("id".equals(property)) {
            bd.getPropertyValues().addPropertyValue("id", id);
            continue;
        }
        String value = element.getAttribute(property);
        if ("methods".equals(property)) {
            parseMethods(id, element.getChildNodes(), bd, parserContext);
        }
        if (StringUtils.isBlank(value)) {
            continue;
        }
        value = value.trim();
        if (value.length() == 0) {
            continue;
        }
        Object reference;
        if ("ref".equals(property)) {
            if (parserContext.getRegistry().containsBeanDefinition(value)) {
                BeanDefinition refBean = parserContext.getRegistry().getBeanDefinition(value);
                if (!refBean.isSingleton()) {
                    throw new IllegalStateException(
                            "The exported service ref " + value + " must be singleton! Please set the " + value
                                    + " bean scope to singleton, eg: <bean id=\"" + value
                                    + "\" scope=\"singleton\" ...>");
                }
            }
            reference = new RuntimeBeanReference(value);
        } else if ("protocol".equals(property) && !StringUtils.isBlank(value)) {
            if (!value.contains(",")) {
                reference = new RuntimeBeanReference(value);
            } else {
                parseMultiRef("protocols", value, bd, parserContext);
                reference = null;
            }
        } else if ("registry".equals(property)) {
            parseMultiRef("registries", value, bd, parserContext);
            reference = null;
        } else if ("basicService".equals(property)) {
            reference = new RuntimeBeanReference(value);

        } else if ("basicReferer".equals(property)) {
            reference = new RuntimeBeanReference(value);

        } else if ("extConfig".equals(property)) {
            reference = new RuntimeBeanReference(value);
        } else {
            reference = new TypedStringValue(value);
        }

        if (reference != null) {
            bd.getPropertyValues().addPropertyValue(property, reference);
        }
    }
    if (ProtocolConfig.class.equals(beanClass)) {
        // protocolparameters?
        NamedNodeMap attributes = element.getAttributes();
        int len = attributes.getLength();
        for (int i = 0; i < len; i++) {
            Node node = attributes.item(i);
            String name = node.getLocalName();
            if (!props.contains(name)) {
                if (parameters == null) {
                    parameters = new ManagedMap();
                }
                String value = node.getNodeValue();
                parameters.put(name, new TypedStringValue(value, String.class));
            }
        }
        bd.getPropertyValues().addPropertyValue("parameters", parameters);
    }
    return bd;
}

From source file:com.igormaznitsa.upom.UPomModel.java

private static Method findMethod(final Class klazz, final String methodName, final boolean onlyPublic) {
    Method result = null;/* ww  w .j  a  v a2 s.co m*/
    for (final Method m : klazz.getMethods()) {
        if (onlyPublic && !Modifier.isPublic(m.getModifiers())) {
            continue;
        }
        if (m.getName().equalsIgnoreCase(methodName)) {
            result = m;
            break;
        }
    }
    return result;
}