Example usage for java.lang Class getSuperclass

List of usage examples for java.lang Class getSuperclass

Introduction

In this page you can find the example usage for java.lang Class getSuperclass.

Prototype

@HotSpotIntrinsicCandidate
public native Class<? super T> getSuperclass();

Source Link

Document

Returns the Class representing the direct superclass of the entity (class, interface, primitive type or void) represented by this Class .

Usage

From source file:com.googlecode.jsonplugin.JSONUtil.java

/**
 * Recursive method to visit all the interfaces of a class (and its superclasses and super-interfaces) if they
 * haven't already been visited.//from  www .  j a v a2 s . c  o m
 * <p/>
 * Always visits itself if it hasn't already been visited
 *
 * @param thisClass      the current class to visit (if not already done so)
 * @param classesVisited classes already visited
 * @param visitor        this vistor is called for each class/interface encountered
 * @return true if recursion can continue, false if it should be aborted
 */
private static boolean visitUniqueInterfaces(Class thisClass, ClassVisitor visitor,
        List<Class> classesVisited) {
    boolean okayToContinue = true;

    if (!classesVisited.contains(thisClass)) {
        classesVisited.add(thisClass);
        okayToContinue = visitor.visit(thisClass);

        if (okayToContinue) {
            Class[] interfaces = thisClass.getInterfaces();
            int index = 0;
            while ((index < interfaces.length) && (okayToContinue)) {
                okayToContinue = visitUniqueInterfaces(interfaces[index++], visitor, classesVisited);
            }

            if (okayToContinue) {
                Class superClass = thisClass.getSuperclass();
                if ((superClass != null) && (!Object.class.equals(superClass))) {
                    okayToContinue = visitUniqueInterfaces(superClass, visitor, classesVisited);
                }
            }
        }
    }
    return okayToContinue;
}

From source file:info.papdt.blacklight.support.Utility.java

public static Method findMethod(Class<?> clazz, String name) throws NoSuchMethodException {
    Class<?> cla = clazz;
    Method method = null;// w w w  .ja va 2 s. c  o m

    do {
        try {
            method = cla.getDeclaredMethod(name);
        } catch (NoSuchMethodException e) {
            method = null;
            cla = cla.getSuperclass();
        }
    } while (method == null && cla != Object.class);

    if (method == null) {
        throw new NoSuchMethodException();
    } else {
        return method;
    }
}

From source file:net.kamhon.ieagle.util.VoUtil.java

/**
 * To upperCase object String field//from   w ww.j  a v  a 2  s  . co  m
 * 
 * @param all
 *            default is false. true means toUpperCase all String field, false toUpperCase the fields have
 *            net.kamhon.ieagle.vo.core.annotation.ToUpperCase.
 * 
 * @param objects
 */
public static void toUpperCaseProperties(boolean all, Object... objects) {
    for (Object object : objects) {
        if (object == null) {
            continue;
        }

        // getter for String field only
        Map<String, Method> getterMap = new HashMap<String, Method>();
        // setter for String field only
        Map<String, Method> setterMap = new HashMap<String, Method>();

        Class<?> clazz = object.getClass();

        Method[] methods = clazz.getMethods();

        for (Method method : methods) {
            /*
             * log.debug("method = " + method.getName());
             * log.debug("method.getParameterTypes().length = " +
             * method.getParameterTypes().length); if
             * (method.getParameterTypes().length == 1)
             * log.debug("method.getParameterTypes()[0] = " +
             * method.getParameterTypes()[0]);
             * log.debug("method.getReturnType() = " +
             * method.getReturnType());
             * log.debug("================================================="
             * );
             */
            if (method.getName().startsWith("get") && method.getParameterTypes().length == 0
                    && method.getReturnType().equals(String.class)) {

                // if method name is getXxx
                String fieldName = method.getName().substring(3);
                fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);

                getterMap.put(fieldName, method);
            } else if (method.getName().startsWith("set") && method.getParameterTypes().length == 1
                    && method.getParameterTypes()[0] == String.class
                    && method.getReturnType().equals(void.class)) {
                // log.debug("setter = " + method.getName());

                // if method name is setXxx
                String fieldName = method.getName().substring(3);
                fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);

                setterMap.put(fieldName, method);
            }
        }

        // if the key exists in both getter & setter
        for (String key : getterMap.keySet()) {
            if (setterMap.containsKey(key)) {
                try {
                    Method getterMethod = getterMap.get(key);
                    Method setterMethod = setterMap.get(key);

                    // if not all, check on Field
                    if (!all) {
                        Field field = null;

                        Class<?> tmpClazz = clazz;
                        // looping up to superclass to get decleared field
                        do {
                            try {
                                field = tmpClazz.getDeclaredField(key);
                            } catch (Exception ex) {
                                // do nothing
                            }

                            if (field != null) {
                                break;
                            }

                            tmpClazz = tmpClazz.getSuperclass();
                        } while (tmpClazz != null);

                        ToUpperCase toUpperCase = field.getAnnotation(ToUpperCase.class);
                        if (toUpperCase == null || toUpperCase.upperCase() == false) {
                            continue;
                        }
                    }

                    String value = (String) getterMethod.invoke(object, new Object[] {});

                    if (StringUtils.isNotBlank(value))
                        setterMethod.invoke(object, value.toUpperCase());

                } catch (Exception ex) {
                    // log.error("Getter Setter for " + key + " has error ", ex);
                }
            }
        }
    }
}

From source file:jp.terasoluna.fw.util.GenericsUtil.java

/**
 * ??????? <code>ParameterizedType</code>???
 * @param <T> ???/*from  ww w  .j  a  va  2s .  com*/
 * @param genericClass ??
 * @param descendantClass <code>genericsClass</code>?? ???
 * @return ??????? <code>ParameterizedType</code>?
 * @throws IllegalStateException <code>descendantClass</code>? ??????????? <code>genercClass</code>
 *             ????? ?????
 */
protected static <T> List<ParameterizedType> getAncestorTypeList(Class<T> genericClass,
        Class<? extends T> descendantClass) throws IllegalStateException {
    List<ParameterizedType> ancestorTypeList = new ArrayList<ParameterizedType>();
    Class<?> clazz = descendantClass;
    boolean isInterface = genericClass.isInterface();

    while (clazz != null) {
        Type type = clazz.getGenericSuperclass();
        if (checkParameterizedType(type, genericClass, ancestorTypeList)) {
            break;
        }

        // ??????
        // ??????
        if (!isInterface) {
            clazz = clazz.getSuperclass();
            continue;
        }
        if (checkInterfaceAncestors(genericClass, ancestorTypeList, clazz)) {
            break;
        }

        // ???????????
        // ????????
        // ?????????????
        // ??????????
        // ???Generics?API?????????????
        // ?????????
        clazz = clazz.getSuperclass();
    }

    // ?????
    // AbstractBLogic<P, R>
    if (ancestorTypeList.isEmpty()) {
        throw new IllegalStateException(
                "Argument 'genericClass'(" + genericClass.getName() + ") does not declare type parameter");
    }

    // ???????????????
    // ??????????
    // ???Generics?API?????????????
    // ?????????
    ParameterizedType targetType = ancestorTypeList.get(ancestorTypeList.size() - 1);
    if (!targetType.getRawType().equals(genericClass)) {
        throw new IllegalStateException("Class(" + descendantClass.getName()
                + ") is not concrete class of Class(" + genericClass.getName() + ")");
    }
    return ancestorTypeList;
}

From source file:JDBCPool.dbcp.demo.sourcecode.PoolImplUtils.java

/**
 * Obtain the concrete type used by an implementation of an interface that
 * uses a generic type./*from w  w w. ja  v a  2  s  .c  o m*/
 *
 * @param type  The interface that defines a generic type
 * @param clazz The class that implements the interface with a concrete type
 * @param <T>   The interface type
 *
 * @return concrete type used by the implementation
 */
private static <T> Object getGenericType(Class<T> type, Class<? extends T> clazz) {

    // Look to see if this class implements the generic interface

    // Get all the interfaces
    Type[] interfaces = clazz.getGenericInterfaces();
    for (Type iface : interfaces) {
        // Only need to check interfaces that use generics
        if (iface instanceof ParameterizedType) {
            ParameterizedType pi = (ParameterizedType) iface;
            // Look for the generic interface
            if (pi.getRawType() instanceof Class) {
                if (type.isAssignableFrom((Class<?>) pi.getRawType())) {
                    return getTypeParameter(clazz, pi.getActualTypeArguments()[0]);
                }
            }
        }
    }

    // Interface not found on this class. Look at the superclass.
    @SuppressWarnings("unchecked")
    Class<? extends T> superClazz = (Class<? extends T>) clazz.getSuperclass();

    Object result = getGenericType(type, superClazz);
    if (result instanceof Class<?>) {
        // Superclass implements interface and defines explicit type for
        // generic
        return result;
    } else if (result instanceof Integer) {
        // Superclass implements interface and defines unknown type for
        // generic
        // Map that unknown type to the generic types defined in this class
        ParameterizedType superClassType = (ParameterizedType) clazz.getGenericSuperclass();
        return getTypeParameter(clazz, superClassType.getActualTypeArguments()[((Integer) result).intValue()]);
    } else {
        // Error will be logged further up the call stack
        return null;
    }
}

From source file:com.springframework.core.annotation.AnnotationUtils.java

/**
 * Find a single {@link Annotation} of {@code annotationType} on the supplied
 * {@link Method}, traversing its super methods (i.e., from superclasses and
 * interfaces) if no annotation can be found on the given method itself.
 * <p>Correctly handles bridge {@link Method Methods} generated by the compiler.
 * <p>Meta-annotations will be searched if the annotation is not
 * <em>directly present</em> on the method.
 * <p>Annotations on methods are not inherited by default, so we need to handle
 * this explicitly./*from  www  . j  av a2  s .co m*/
 * @param method the method to look for annotations on
 * @param annotationType the annotation type to look for
 * @return the matching annotation, or {@code null} if not found
 * @see #getAnnotation(Method, Class)
 */
@SuppressWarnings("unchecked")
public static <A extends Annotation> A findAnnotation(Method method, Class<A> annotationType) {
    AnnotationCacheKey cacheKey = new AnnotationCacheKey(method, annotationType);
    A result = (A) findAnnotationCache.get(cacheKey);

    if (result == null) {
        Method resolvedMethod = BridgeMethodResolver.findBridgedMethod(method);
        result = findAnnotation((AnnotatedElement) resolvedMethod, annotationType);

        if (result == null) {
            result = searchOnInterfaces(method, annotationType, method.getDeclaringClass().getInterfaces());
        }

        Class<?> clazz = method.getDeclaringClass();
        while (result == null) {
            clazz = clazz.getSuperclass();
            if (clazz == null || clazz.equals(Object.class)) {
                break;
            }
            try {
                Method equivalentMethod = clazz.getDeclaredMethod(method.getName(), method.getParameterTypes());
                Method resolvedEquivalentMethod = BridgeMethodResolver.findBridgedMethod(equivalentMethod);
                result = findAnnotation((AnnotatedElement) resolvedEquivalentMethod, annotationType);
            } catch (NoSuchMethodException ex) {
                // No equivalent method found
            }
            if (result == null) {
                result = searchOnInterfaces(method, annotationType, clazz.getInterfaces());
            }
        }

        if (result != null) {
            findAnnotationCache.put(cacheKey, result);
        }
    }

    return result;
}

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

private static Method _findMethod(Class<?> clazz, String methodName, Class<?>[] parameterTypes)
        throws NoSuchMethodException {
    Method method = null;/*  w  w  w  . ja  va2s  . co m*/
    try {
        method = clazz.getMethod(methodName, parameterTypes);
    } catch (NoSuchMethodException e) {
        try {
            method = clazz.getDeclaredMethod(methodName, parameterTypes);
        } catch (NoSuchMethodException ignore) {
        }
    }
    if (method == null) {
        Class<?> superClazz = clazz.getSuperclass();
        if (superClazz != null) {
            method = _findMethod(superClazz, methodName, parameterTypes);
        }
        if (method == null) {
            throw new NoSuchMethodException("Method: " + methodName);
        } else {
            return method;
        }
    } else {
        return method;
    }
}

From source file:com.helpinput.utils.Utils.java

public static Field findField(Class<?> targetClass, String fieldName) {
    Field theField;// w  ww  . ja va  2  s.  c  om
    try {
        theField = targetClass.getDeclaredField(fieldName);
        return accessible(theField);
    } catch (NoSuchFieldException e) {
        if (targetClass.getSuperclass() != null)
            return findField(targetClass.getSuperclass(), fieldName);
        else
            return null;
    }
}

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

private static Field findDeclaredFieldForName(final Class klazz, final String fieldName) {
    Field result = null;/* w w w. j a v  a 2s. c om*/
    Class curr = klazz;
    while (curr.getName().startsWith(MAVEN_MODEL_PACKAGE_PREFIX)) {
        for (final Field m : curr.getDeclaredFields()) {
            if (m.getName().equalsIgnoreCase(fieldName)) {
                result = m;
                break;
            }
        }
        if (result != null) {
            result.setAccessible(true);
            break;
        }
        curr = klazz.getSuperclass();
    }
    return result;
}

From source file:HashCodeAssist.java

/**
 * <p>/*from   www  . j  a va  2s  .co  m*/
 * This method uses reflection to build a valid hash code.
 * </p>
 * 
 * <p>
 * It uses <code>AccessibleObject.setAccessible</code> to gain access to
 * private fields. This means that it will throw a security exception if run
 * under a security manager, if the permissions are not set up correctly. It
 * is also not as efficient as testing explicitly.
 * </p>
 * 
 * <p>
 * If the TestTransients parameter is set to <code>true</code>, transient
 * members will be tested, otherwise they are ignored, as they are likely
 * derived fields, and not part of the value of the <code>Object</code>.
 * </p>
 * 
 * <p>
 * Static fields will not be included. Superclass fields will be included up
 * to and including the specified superclass. A null superclass is treated
 * as java.lang.Object.
 * </p>
 * 
 * <p>
 * Two randomly chosen, non-zero, odd numbers must be passed in. Ideally
 * these should be different for each class, however this is not vital.
 * Prime numbers are preferred, especially for the multiplier.
 * </p>
 * 
 * @param initialNonZeroOddNumber
 *            a non-zero, odd number used as the initial value
 * @param multiplierNonZeroOddNumber
 *            a non-zero, odd number used as the multiplier
 * @param object
 *            the Object to create a <code>hashCode</code> for
 * @param testTransients
 *            whether to include transient fields
 * @param reflectUpToClass
 *            the superclass to reflect up to (inclusive), may be
 *            <code>null</code>
 * @param excludeFields
 *            array of field names to exclude from use in calculation of
 *            hash code
 * @return int hash code
 * @throws IllegalArgumentException
 *             if the Object is <code>null</code>
 * @throws IllegalArgumentException
 *             if the number is zero or even
 * @since 2.0
 */
public static int reflectionHashCode(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, Object object,
        boolean testTransients, Class<?> reflectUpToClass, String... excludeFields) {

    if (object == null) {
        throw new IllegalArgumentException("The object to build a hash code for must not be null");
    }
    HashCodeAssist builder = new HashCodeAssist(initialNonZeroOddNumber, multiplierNonZeroOddNumber);
    Class<?> clazz = object.getClass();
    reflectionAppend(object, clazz, builder, testTransients, excludeFields);
    while (clazz.getSuperclass() != null && clazz != reflectUpToClass) {
        clazz = clazz.getSuperclass();
        reflectionAppend(object, clazz, builder, testTransients, excludeFields);
    }
    return builder.toHashCode();
}