Example usage for java.lang.reflect Method getName

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

Introduction

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

Prototype

@Override
public String getName() 

Source Link

Document

Returns the name of the method represented by this Method object, as a String .

Usage

From source file:com.evolveum.midpoint.report.impl.ReportUtils.java

public static String prettyPrintForReport(Object value) {
    if (value == null) {
        return "";
    }//from  w  w w. ja v a2  s  .c  o m

    if (value instanceof MetadataType) {
        return "";
    }

    //special handling for byte[], some problems with jasper when printing 
    if (byte[].class.equals(value.getClass())) {
        return prettyPrintForReport((byte[]) value);
    }

    // 1. Try to find prettyPrintForReport in this class first
    if (value instanceof Containerable) { //e.g. RoleType needs to be converted to PCV in order to format properly
        value = (((Containerable) value).asPrismContainerValue());
    }

    for (Method method : ReportUtils.class.getMethods()) {
        if (method.getName().equals("prettyPrintForReport")) {
            Class<?>[] parameterTypes = method.getParameterTypes();
            if (parameterTypes.length == 1 && parameterTypes[0].equals(value.getClass())) {
                try {
                    return (String) method.invoke(null, value);
                } catch (Throwable e) {
                    return "###INTERNAL#ERROR### " + e.getClass().getName() + ": " + e.getMessage()
                            + "; prettyPrintForReport method for value " + value;
                }
            }
        }
    }

    // 2. Default to PrettyPrinter.prettyPrint
    String str = PrettyPrinter.prettyPrint(value);
    if (str.length() > 1000) {
        return str.substring(0, 1000);
    }
    return str;

}

From source file:com.twinsoft.convertigo.beans.CheckBeans.java

private static void analyzeJavaClass(String javaClassName) {
    try {//  w w w. j  a  v  a  2s  .c o  m
        Class<?> javaClass = Class.forName(javaClassName);
        String javaClassSimpleName = javaClass.getSimpleName();

        if (!DatabaseObject.class.isAssignableFrom(javaClass)) {
            //Error.NON_DATABASE_OBJECT.add(javaClassName);
            return;
        }

        nBeanClass++;

        String dboBeanInfoClassName = javaClassName + "BeanInfo";
        MySimpleBeanInfo dboBeanInfo = null;
        try {
            dboBeanInfo = (MySimpleBeanInfo) (Class.forName(dboBeanInfoClassName)).newInstance();
        } catch (ClassNotFoundException e) {
            if (!Modifier.isAbstract(javaClass.getModifiers())) {
                Error.MISSING_BEAN_INFO
                        .add(javaClassName + " (expected bean info: " + dboBeanInfoClassName + ")");
            }
            return;
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        BeanDescriptor beanDescriptor = dboBeanInfo.getBeanDescriptor();

        // Check abstract class
        if (Modifier.isAbstract(javaClass.getModifiers())) {
            // Check icon (16x16)
            String declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo,
                    MySimpleBeanInfo.ICON_COLOR_16x16);
            if (declaredIconName != null) {
                Error.ABSTRACT_CLASS_WITH_ICON.add(javaClassName);
            }

            // Check icon (32x32)
            declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_32x32);
            if (declaredIconName != null) {
                Error.ABSTRACT_CLASS_WITH_ICON.add(javaClassName);
            }

            // Check display name
            if (!beanDescriptor.getDisplayName().equals("?")) {
                Error.ABSTRACT_CLASS_WITH_DISPLAY_NAME.add(javaClassName);
            }

            // Check description
            if (!beanDescriptor.getShortDescription().equals("?")) {
                Error.ABSTRACT_CLASS_WITH_DESCRIPTION.add(javaClassName);
            }
        } else {
            nBeanClassNotAbstract++;

            // Check bean declaration in database_objects.xml
            if (!dboXmlDeclaredDatabaseObjects.contains(javaClassName)) {
                Error.BEAN_DEFINED_BUT_NOT_USED.add(javaClassName);
            }

            // Check icon name policy (16x16)
            String declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo,
                    MySimpleBeanInfo.ICON_COLOR_16x16);
            String expectedIconName = javaClassName.replace(javaClassSimpleName,
                    "images/" + javaClassSimpleName);
            expectedIconName = "/" + expectedIconName.replace('.', '/') + "_color_16x16";
            expectedIconName = expectedIconName.toLowerCase() + ".png";
            if (declaredIconName != null) {
                if (!declaredIconName.equals(expectedIconName)) {
                    Error.BEAN_ICON_NAMING_POLICY.add(javaClassName + "\n" + "      Declared: "
                            + declaredIconName + "\n" + "      Expected: " + expectedIconName);
                }
            }

            // Check icon file (16x16)
            File iconFile = new File(srcBase + declaredIconName);
            if (!iconFile.exists()) {
                Error.BEAN_MISSING_ICON.add(javaClassName + " - icon missing: " + declaredIconName);
            } else {
                icons.remove(declaredIconName);
            }

            // Check icon name policy (32x32)
            declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_32x32);
            expectedIconName = javaClassName.replace(javaClassSimpleName, "images/" + javaClassSimpleName);
            expectedIconName = "/" + expectedIconName.replace('.', '/') + "_color_32x32";
            expectedIconName = expectedIconName.toLowerCase() + ".png";
            if (declaredIconName != null) {
                if (!declaredIconName.equals(expectedIconName)) {
                    Error.BEAN_ICON_NAMING_POLICY.add(javaClassName + "\n" + "      Declared: "
                            + declaredIconName + "\n" + "      Expected: " + expectedIconName);
                }
            }

            // Check icon file (32x32)
            iconFile = new File(srcBase + declaredIconName);
            if (!iconFile.exists()) {
                Error.BEAN_MISSING_ICON.add(javaClassName + " - icon missing: " + declaredIconName);
            } else {
                icons.remove(declaredIconName);
            }

            // Check display name
            if (beanDescriptor.getDisplayName().equals("?")) {
                Error.BEAN_MISSING_DISPLAY_NAME.add(javaClassName);
            }

            // Check description
            if (beanDescriptor.getShortDescription().equals("?")) {
                Error.BEAN_MISSING_DESCRIPTION.add(javaClassName);
            }
        }

        // Check declared bean properties
        PropertyDescriptor[] propertyDescriptors = dboBeanInfo.getLocalPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            String propertyName = propertyDescriptor.getName();
            try {
                javaClass.getDeclaredField(propertyName);
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                try {
                    // Try to find it in the upper classes
                    javaClass.getField(propertyName);
                } catch (SecurityException e1) {
                    // printStackTrace();
                } catch (NoSuchFieldException e1) {
                    Error.PROPERTY_DECLARED_BUT_NOT_FOUND.add(javaClassName + ": " + propertyName);
                }
            }
        }

        Method[] methods = javaClass.getDeclaredMethods();
        List<Method> listMethods = Arrays.asList(methods);
        List<String> listMethodNames = new ArrayList<String>();
        for (Method method : listMethods) {
            listMethodNames.add(method.getName());
        }

        Field[] fields = javaClass.getDeclaredFields();

        for (Field field : fields) {
            int fieldModifiers = field.getModifiers();

            // Ignore static fields (constants)
            if (Modifier.isStatic(fieldModifiers))
                continue;

            String fieldName = field.getName();

            String errorMessage = javaClassName + ": " + field.getName();

            // Check bean info
            PropertyDescriptor propertyDescriptor = isBeanProperty(fieldName, dboBeanInfo);
            if (propertyDescriptor != null) {
                // Check bean property name policy
                if (!propertyDescriptor.getName().equals(fieldName)) {
                    Error.PROPERTY_NAMING_POLICY.add(errorMessage);
                }

                String declaredGetter = propertyDescriptor.getReadMethod().getName();
                String declaredSetter = propertyDescriptor.getWriteMethod().getName();

                String formattedFieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
                String expectedGetter = "get" + formattedFieldName;
                String expectedSetter = "set" + formattedFieldName;

                // Check getter name policy
                if (!declaredGetter.equals(expectedGetter)) {
                    Error.GETTER_SETTER_DECLARED_EXPECTED_NAMES_MISMATCH
                            .add(errorMessage + "\n" + "      Declared getter: " + declaredGetter + "\n"
                                    + "      Expected getter: " + expectedGetter);
                }

                // Check setter name policy
                if (!declaredSetter.equals(expectedSetter)) {
                    Error.GETTER_SETTER_DECLARED_EXPECTED_NAMES_MISMATCH
                            .add(errorMessage + "\n" + "      Declared setter: " + declaredSetter + "\n"
                                    + "      Expected setter: " + expectedSetter);
                }

                // Check required private modifiers for bean property
                if (!Modifier.isPrivate(fieldModifiers)) {
                    Error.PROPERTY_NOT_PRIVATE.add(errorMessage);
                }

                // Check getter
                if (!listMethodNames.contains(declaredGetter)) {
                    Error.GETTER_SETTER_DECLARED_BUT_NOT_FOUND
                            .add(errorMessage + " - Declared getter not found: " + declaredGetter);
                }

                // Check setter
                if (!listMethodNames.contains(declaredSetter)) {
                    Error.GETTER_SETTER_DECLARED_BUT_NOT_FOUND
                            .add(errorMessage + " - Declared setter not found: " + declaredGetter);
                }

                // Check non transient modifier
                if (Modifier.isTransient(fieldModifiers)) {
                    Error.PROPERTY_TRANSIENT.add(errorMessage);
                }
            } else if (!Modifier.isTransient(fieldModifiers)) {
                Error.FIELD_NOT_TRANSIENT.add(errorMessage);
            }
        }
    } catch (ClassNotFoundException e) {
        System.out.println("ERROR on " + javaClassName);
        e.printStackTrace();
    }
}

From source file:Mopex.java

/**
 * Determines if the signatures of two method objects are equal. In Java, a
 * signature comprises the method name and the array of of formal parameter
 * types. For two signatures to be equal, the method names must be the same
 * and the formal parameters must be of the same type (in the same order).
 * //from   w  w  w .  j a  v a  2 s.c  o  m
 * @return boolean
 * @param m1
 *            java.lang.Method
 * @param m2
 *            java.lang.Method
 */
//start extract equalSignatures
public static boolean equalSignatures(Method m1, Method m2) {
    if (!m1.getName().equals(m2.getName()))
        return false;
    if (!Arrays.equals(m1.getParameterTypes(), m2.getParameterTypes()))
        return false;
    return true;
}

From source file:springfox.documentation.schema.property.bean.Accessors.java

public static String propertyName(Method method) {
    Optional<JsonGetter> jsonGetterAnnotation = getterAnnotation(method);
    if (jsonGetterAnnotation.isPresent() && !isNullOrEmpty(jsonGetterAnnotation.get().value())) {
        return jsonGetterAnnotation.get().value();
    }/*from   ww w  .  j  a v a 2s .c  om*/
    Optional<JsonSetter> jsonSetterAnnotation = setterAnnotation(method);
    if (jsonSetterAnnotation.isPresent() && !isNullOrEmpty(jsonSetterAnnotation.get().value())) {
        return jsonSetterAnnotation.get().value();
    }
    Matcher matcher = getter.matcher(method.getName());
    if (matcher.find()) {
        return toCamelCase(matcher.group(1));
    }
    matcher = isGetter.matcher(method.getName());
    if (matcher.find()) {
        return toCamelCase(matcher.group(1));
    }
    matcher = setter.matcher(method.getName());
    if (matcher.find()) {
        return toCamelCase(matcher.group(1));
    }
    return "";
}

From source file:com.softmotions.commons.bean.BeanUtils.java

/**
 * Invokes a getter method with the given value.
 *
 * @param bean         The bean to set a property at.
 * @param getterMethod The setter method to invoke.
 * @return The determined value./*  ww  w.  j  a va  2 s .com*/
 * @throws BeanException In case the bean access failed.
 */
public static Object invokeGetter(Object bean, Method getterMethod) throws BeanException {
    if (bean == null) {
        return null;
    }
    try {
        return getterMethod.invoke(bean, GETTER_ARGS);
    } catch (InvocationTargetException | IllegalAccessException | IllegalArgumentException ex) {
        throw new BeanException("Failed to call getter method '" + getterMethod.getName()
                + "' for given bean from class " + bean.getClass().getName() + ".", ex);
    }
}

From source file:com.google.code.siren4j.util.ReflectionUtils.java

/**
 * Retrieve the setter for the specified class/field if it exists.
 *
 * @param clazz//  w ww.j a  v  a 2 s  .c o m
 * @param f
 * @return
 */
public static Method getSetter(Class<?> clazz, Field f) {
    Method setter = null;
    for (Method m : clazz.getMethods()) {
        if (ReflectionUtils.isSetter(m)
                && m.getName().equals(SETTER_PREFIX + StringUtils.capitalize(f.getName()))) {
            setter = m;
            break;
        }
    }
    return setter;
}

From source file:com.smart.utils.ReflectionUtils.java

/**
 * ?????,danfo/*from  w w  w  . j  a  v  a 2  s. com*/
 * 
 * @param bean
 * @param methodName
 * @param args
 * @return
 */
public static Method getMethodOfBeanByName(Object bean, String methodName, Object[] args) {

    if (bean == null || methodName == null) {
        return null;
    }
    if (args == null) {
        Object[] paras = {};
        args = paras;
    }
    Method method = null;
    Class beanClass = bean.getClass();
    Method[] methods = beanClass.getMethods();
    for (int i = methods.length - 1; i >= 0; i--) {
        Method methodTemp = (Method) methods[i];
        String methodNameTemp = methodTemp.getName();
        // ??,??
        if (methodName.equals(methodNameTemp)) {
            Class[] paras = methodTemp.getParameterTypes();
            // ??
            if (paras.length != args.length) {
                continue;
            }
            // ,???
            boolean isParaTheSame = true;
            for (int j = paras.length - 1; j >= 0; j--) {
                Class paraNeededClass = paras[j];
                Class paraGivenClass = args[j].getClass();
                if (!paraNeededClass.getName().equals(paraGivenClass.getName())) {
                    isParaTheSame = false;
                    break;
                }
            }
            if (isParaTheSame) {
                method = methodTemp;
            }
        }
    }
    return method;
    // end of methodNameargs
}

From source file:cop.raml.mocks.MockUtils.java

public static ExecutableElementMock createExecutable(Method method) {
    if (method == null)
        return null;

    boolean isStatic = Modifier.isStatic(method.getModifiers());
    String params = Arrays.stream(method.getParameterTypes()).map(Class::getSimpleName)
            .collect(Collectors.joining(","));
    String name = String.format("(%s)%s", params, method.getReturnType().getSimpleName());

    return new ExecutableElementMock(method.getName() + "()", createMethodElement(name).asType())
            .setStatic(isStatic).setSimpleName(method.getName());
}

From source file:com.heliosphere.athena.base.resource.bundle.ResourceBundleManager.java

/**
 * Returns the resource bundle string of a given enumerated value for the given enumeration class. This
 * method is generally used by enumeration classes using the {@code BundleEnum} annotation.
 * <hr>/*from   w ww . j ava2s  .c o m*/
 * @param eClass Class of the enumeration.
 * @param e Enumerated value.
 * @param locale {@link Locale} to use for resource string retrieval.
 * @return Resource bundle string.
 */
@SuppressWarnings("nls")
public static final String getResourceForMethodName(@NonNull final Class<? extends Enum<?>> eClass,
        final Enum<?> e, final Locale locale) {
    String key = null;
    ResourceBundle bundle;
    String methodName = null;
    String className;

    int index = 1;
    boolean found = false;
    while (!found) {
        className = Thread.currentThread().getStackTrace()[index].getClassName();
        if (className.equals(eClass.getName())) {
            methodName = Thread.currentThread().getStackTrace()[index].getMethodName();
            found = true;
        } else {
            index++;
        }
    }

    if (found) {
        for (Method method : eClass.getMethods()) {
            BundleEnum annotation = method.getAnnotation(BundleEnum.class);
            if (annotation != null && method.getName().equals(methodName)) {
                bundle = ResourceBundle.getBundle(annotation.file(), locale);
                key = annotation.path() + "." + e.name();
                return bundle.getString(key);
            }
        }
    }

    throw new ResourceBundleException(BundleAthenaBase.ResourceBundleInvalidKey, null, key, null, locale, e);
}

From source file:com.heliosphere.demeter.base.resource.bundle.ResourceBundleManager.java

/**
 * Returns the resource bundle string of a given enumerated value for the given enumeration class. This
 * method is generally used by enumeration classes using the {@code BundleEnum} annotation.
 * <hr>//from   w w  w  .  j  a  v a 2s.co m
 * @param eClass Class of the enumeration.
 * @param e Enumerated value.
 * @param locale {@link Locale} to use for resource string retrieval.
 * @return Resource bundle string.
 */
@SuppressWarnings("nls")
public static final String getResourceForMethodName(@NonNull final Class<? extends Enum<?>> eClass,
        final Enum<?> e, final Locale locale) {
    String key = null;
    ResourceBundle bundle;
    String methodName = null;
    String className;

    int index = 1;
    boolean found = false;
    while (!found) {
        className = Thread.currentThread().getStackTrace()[index].getClassName();
        if (className.equals(eClass.getName())) {
            methodName = Thread.currentThread().getStackTrace()[index].getMethodName();
            found = true;
        } else {
            index++;
        }
    }

    if (found) {
        for (Method method : eClass.getMethods()) {
            BundleEnum annotation = method.getAnnotation(BundleEnum.class);
            if (annotation != null && method.getName().equals(methodName)) {
                bundle = ResourceBundle.getBundle(annotation.file(), locale);
                key = annotation.path() + "." + e.name();
                return bundle.getString(key);
            }
        }
    }

    throw new ResourceBundleException(BundleDemeterBase.ResourceBundleInvalidKey, null, key, null, locale, e);
}