Example usage for java.lang.reflect Method getDeclaringClass

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

Introduction

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

Prototype

@Override
public Class<?> getDeclaringClass() 

Source Link

Document

Returns the Class object representing the class or interface that declares the method represented by this object.

Usage

From source file:com.espertech.esper.event.vaevent.PropertyUtility.java

public static PropertyAccessException getMismatchException(Method method, Object object, ClassCastException e) {
    return getMismatchException(method.getDeclaringClass(), object, e);
}

From source file:api.wiki.WikiGenerator.java

private static String hyperLink(Method apiMethod) {
    String className = apiMethod.getDeclaringClass().getSimpleName();
    String pageLocation = className + "/" + pageName(apiMethod);
    return hyperLink(methodDisplayName(apiMethod), pageLocation);
}

From source file:com.mawujun.utils.bean.BeanUtils.java

/**
 * ????//  www.  j a  v a 2s  .  com
 * null
 * @param source
 * @param target
 * @throws BeansException
 * @throws IntrospectionException
 */
public static void copyExcludeNull(Object source, Object target) throws IntrospectionException {

    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");

    Class<?> actualEditable = target.getClass();

    PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);

    for (PropertyDescriptor targetPd : targetPds) {
        if (targetPd.getWriteMethod() != null) {
            PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
            if (sourcePd != null && sourcePd.getReadMethod() != null) {
                try {
                    Method readMethod = sourcePd.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }
                    Object value = readMethod.invoke(source);
                    if (value == null) {//??
                        continue;
                    }
                    Method writeMethod = targetPd.getWriteMethod();
                    if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                        writeMethod.setAccessible(true);
                    }
                    writeMethod.invoke(target, value);
                } catch (Throwable ex) {
                    throw new RuntimeException("Could not copy properties from source to target", ex);
                }
            }
        }
    }
}

From source file:io.dyn.core.handler.Handlers.java

public static String findEventName(Method method) {
    On on = find(On.class, method);
    if (null != on) {
        return on.value();
    } else if (null != AnnotationUtils.findAnnotation(method.getDeclaringClass(), Handler.class)) {
        return method.getName();
    }/*from ww  w .  ja va  2  s  .  co  m*/
    return null;
}

From source file:Main.java

/**
 * find all getter and is method and return the value by map.
 *//*from w w w . j  a  v  a  2  s  .c  o  m*/
public static Map<String, Object> getProperties(Object bean) {
    Map<String, Object> map = new HashMap<>();
    for (Method method : bean.getClass().getMethods()) {
        String name = method.getName();
        if (((name.length() > 3 && name.startsWith("get")) || (name.length() > 2 && name.startsWith("is")))
                && Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0
                && method.getDeclaringClass() != Object.class) {
            int i = name.startsWith("get") ? 3 : 2;
            String key = name.substring(i, i + 1).toLowerCase() + name.substring(i + 1);
            try {
                map.put(key, method.invoke(bean, new Object[0]));
            } catch (Exception e) {
            }
        }
    }
    return map;
}

From source file:jp.primecloud.auto.util.StringUtils.java

public static String reflectToString(Object object) {
    if (object == null) {
        return null;
    }/* ww w.  j av  a 2s  .  c  om*/

    // String??
    if (object instanceof String) {
        return (String) object;
    }

    // ??
    if (object instanceof Number) {
        return object.toString();
    }

    // Boolean??
    if (object instanceof Boolean) {
        return object.toString();
    }

    // Character??
    if (object instanceof Character) {
        return object.toString();
    }

    // ???
    if (object instanceof Object[]) {
        return reflectToString(Arrays.asList((Object[]) object));
    }

    // ??
    if (object instanceof Collection<?>) {
        Iterator<?> iterator = ((Collection<?>) object).iterator();
        if (!iterator.hasNext()) {
            return "[]";
        }

        StringBuilder str = new StringBuilder();
        str.append("[");
        while (true) {
            Object object2 = iterator.next();
            str.append(reflectToString(object2));
            if (!iterator.hasNext()) {
                break;
            }
            str.append(", ");
        }
        str.append("]");
        return str.toString();
    }

    // ??
    if (object instanceof Map<?, ?>) {
        Iterator<?> iterator = ((Map<?, ?>) object).entrySet().iterator();
        if (!iterator.hasNext()) {
            return "{}";
        }

        StringBuilder str = new StringBuilder();
        str.append("{");
        while (true) {
            Object entry = iterator.next();
            str.append(reflectToString(entry));
            if (!iterator.hasNext()) {
                break;
            }
            str.append(", ");
        }
        str.append("}");
        return str.toString();
    }

    // Entry??
    if (object instanceof Entry<?, ?>) {
        Entry<?, ?> entry = (Entry<?, ?>) object;
        StringBuilder str = new StringBuilder();
        str.append(reflectToString(entry.getKey()));
        str.append("=");
        str.append(reflectToString(entry.getValue()));
        return str.toString();
    }

    // toString?????
    try {
        Method method = object.getClass().getMethod("toString");
        if (!Object.class.equals(method.getDeclaringClass())) {
            return object.toString();
        }
    } catch (NoSuchMethodException ignore) {
    }

    // ?????
    try {
        PropertyDescriptor[] descriptors = Introspector.getBeanInfo(object.getClass()).getPropertyDescriptors();
        StringBuilder str = new StringBuilder();
        str.append("[");
        for (PropertyDescriptor descriptor : descriptors) {
            if ("class".equals(descriptor.getName())) {
                continue;
            }

            Method readMethod = descriptor.getReadMethod();
            if (readMethod == null) {
                continue;
            }

            if (str.length() > 1) {
                str.append(", ");
            }
            Object object2 = readMethod.invoke(object);
            str.append(descriptor.getName()).append("=").append(reflectToString(object2));
        }
        str.append("]");
        return str.toString();
    } catch (IntrospectionException ignore) {
    } catch (InvocationTargetException ignore) {
    } catch (IllegalAccessException ignore) {
    }

    // ????????commons-lang?
    return ReflectionToStringBuilder.toString(object);
}

From source file:Main.java

public static Map<String, Object> getProperties(Object bean) {
    Map<String, Object> map = new HashMap<String, Object>();
    for (Method method : bean.getClass().getMethods()) {
        String name = method.getName();
        if ((name.length() > 3 && name.startsWith("get") || name.length() > 2 && name.startsWith("is"))
                && Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0
                && method.getDeclaringClass() != Object.class) {
            int i = name.startsWith("get") ? 3 : 2;
            String key = name.substring(i, i + 1).toLowerCase() + name.substring(i + 1);
            try {
                map.put(key, method.invoke(bean, new Object[0]));
            } catch (Exception e) {
            }//from  ww  w  .j  a  va2  s  .  co  m
        }
    }
    return map;
}

From source file:com.xemantic.tadedon.guice.persistence.PersistenceUtils.java

/**
 * Checks {@link Transactional#readOnly()} property for given {@code method}.
 * <p>/*w ww.jav a2 s .  c o m*/
 * Algorithm starts with method annotation checking also overridden methods
 * from supertypes. If no annotation is found on the {@code method}, annotation
 * of declaring class and it's supertypes will be used. Absence of any
 * {@code Transactional} annotation will cause {@link IllegalArgumentException}.
 *
 * @param method the method starting transaction.
 * @return {@code true} if method should be run in read-only transaction, {@code false}
 *          otherwise.
 * @throws IllegalArgumentException if no {@link Transactional} annotation is found
 *          either on the {@code method}}, or on declaring class.
 */
public static boolean isTransactionReadOnly(Method method) {
    final Transactional methodTransactional = AnnotationUtils.findAnnotation(method, Transactional.class);
    final boolean readOnly;
    if (methodTransactional != null) {
        readOnly = methodTransactional.readOnly();
    } else {
        final Class<?> klass = method.getDeclaringClass();
        final Transactional classTransactional = klass.getAnnotation(Transactional.class);
        checkNotNull(classTransactional,
                "Either method or declaring class should be annotated @Transacetional, method: %s", method);
        readOnly = classTransactional.readOnly();
    }
    return readOnly;
}

From source file:com.zigbee.framework.common.util.BeanCopyUtil.java

/**
 * Override copyProperties Method/* ww  w . j av  a 2 s  .c o m*/
 * @Date        :      2011-8-5
 * @param source source bean instance
 * @param target destination bean instance
 */
public static void copyProperties(Object source, Object target) {
    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");
    Class<?> actualEditable = target.getClass();
    PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
    for (PropertyDescriptor targetPd : targetPds) {
        if (targetPd.getWriteMethod() != null) {

            try {
                PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                if (sourcePd != null && sourcePd.getReadMethod() != null) {
                    Method readMethod = sourcePd.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }
                    Object value = readMethod.invoke(source);
                    //Check whether the value is empty, only copy the properties which are not empty
                    if (value != null) {
                        Method writeMethod = targetPd.getWriteMethod();
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        writeMethod.invoke(target, value);
                    }

                }
            } catch (BeansException e) {
                e.printStackTrace();
                String errMsg = "BEAN COPY Exception!" + e.getMessage();
                logger.error(errMsg);

            } catch (SecurityException e) {
                e.printStackTrace();
                String errMsg = "BEAN COPY Exception!" + e.getMessage();
                logger.error(errMsg);

            } catch (IllegalArgumentException e) {
                e.printStackTrace();
                String errMsg = "BEAN COPY Exception!" + e.getMessage();
                logger.error(errMsg);

            } catch (IllegalAccessException e) {
                e.printStackTrace();
                String errMsg = "BEAN COPY Exception!" + e.getMessage();
                logger.error(errMsg);

            } catch (InvocationTargetException e) {
                e.printStackTrace();
                String errMsg = "BEAN COPY Exception!" + e.getMessage();
                logger.error(errMsg);

            }

        }
    }
}

From source file:com.cloudera.csd.validation.references.components.ReflectionHelper.java

/**
 * Return the set of getter methods for the class.
 *
 * @param clazz the class.// www .j  a  v a2s.c o  m
 * @return the set of getter methods.
 */
public static Set<Method> getterMethods(Class<?> clazz) {
    Preconditions.checkNotNull(clazz);
    try {
        ImmutableSet.Builder<Method> builder = ImmutableSet.builder();
        BeanInfo info = Introspector.getBeanInfo(clazz);
        for (PropertyDescriptor p : info.getPropertyDescriptors()) {
            Method getter = p.getReadMethod();
            if (getter != null) {
                // Don't want to include any of the methods inherited from object.
                if (!getter.getDeclaringClass().equals(Object.class)) {
                    builder.add(getter);
                }
            }
        }
        return builder.build();
    } catch (IntrospectionException e) {
        throw new IllegalStateException("Could not introspect on " + clazz, e);
    }
}