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.google.code.simplestuff.bean.BusinessObjectContext.java

/**
 * Retrieve a {@link BusinessObjectDescriptor} object for a
 * {@link BusinessObject} class bean./*from w ww .  j  a  v  a2 s  . co  m*/
 * 
 * @param objectClass The class of the bean to check.
 * @param annotationObjectClass The class to use for retrieving the
 *        {@link BusinessField} annotated field.
 * @return A {@link BusinessObjectDescriptor} for the bean class passed.
 */
private static BusinessObjectDescriptor getBusinessObjectDescriptor(Class<? extends Object> objectClass,
        Class<? extends Object> annotationObjectClass) {

    BusinessObjectDescriptor businessObjectDescriptor = new BusinessObjectDescriptor();

    if (objectClass == null) {
        businessObjectDescriptor.setNearestBusinessObjectClass(null);
        return businessObjectDescriptor;
    } else {
        if (objectClass.isAnnotationPresent(BusinessObject.class)) {

            businessObjectDescriptor.setAnnotatedFields(getAnnotatedFields(annotationObjectClass));
            businessObjectDescriptor.setClassToBeConsideredInComparison(
                    objectClass.getAnnotation(BusinessObject.class).includeClassAsBusinessField());
            businessObjectDescriptor.setNearestBusinessObjectClass(objectClass);
            return businessObjectDescriptor;
        } else {
            return getBusinessObjectDescriptor(objectClass.getSuperclass(), annotationObjectClass);
        }

    }
}

From source file:arena.utils.ReflectionUtils.java

public static String[] getAttributeNamesUsingGetter(Class<?> entityClass) {
    //        return BeanUtils.getPropertyDescriptors(entityClass);
    Class<?> clsMe = entityClass;
    List<String> voFieldNames = new ArrayList<String>();

    while (clsMe != null) {
        Field[] fields = clsMe.getDeclaredFields();

        for (int n = 0; n < fields.length; n++) {
            int modifiers = fields[n].getModifiers();
            if (!Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers)) {
                String fieldName = fields[n].getName();
                try {
                    PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(entityClass, fieldName);
                    if (pd.getReadMethod() != null) {
                        voFieldNames.add(fieldName);
                    }/*  w  w  w  .  j av  a 2  s  .co m*/
                } catch (Throwable err) {
                    // skip
                }
            }
        }

        // Loop back to parent class
        clsMe = clsMe.getSuperclass();
    }
    return voFieldNames.toArray(new String[voFieldNames.size()]);
}

From source file:com.github.helenusdriver.commons.lang3.reflect.ReflectionUtils.java

/**
 * Finds the first class from a given class' hierarchy that is annotated
 * with the specified annotation.//from  w w w  .  ja  v  a2 s.c om
 *
 * @author paouelle
 *
 * @param <T> the type of the class to start searching from
 *
 * @param  clazz the class from which to search
 * @param  annotationClass the annotation to search for
 * @return the first class in <code>clazz</code>'s hierarchy annotated with
 *         the specified annotation or <code>null</code> if none is found
 * @throws NullPointerException if <code>clazz</code> or
 *         <code>annotationClass</code> is <code>null</code>
 */
public static <T> Class<? super T> findFirstClassAnnotatedWith(Class<T> clazz,
        Class<? extends Annotation> annotationClass) {
    org.apache.commons.lang3.Validate.notNull(clazz, "invalid null class");
    org.apache.commons.lang3.Validate.notNull(annotationClass, "invalid null annotation class");
    Class<? super T> c = clazz;

    do {
        if (c.getDeclaredAnnotationsByType(annotationClass).length > 0) {
            return c;
        }
        c = c.getSuperclass();
    } while (c != null);
    return null;
}

From source file:de.javakaffee.web.msm.integration.TestUtils.java

public static void assertDeepEquals(final Object one, final Object another,
        final Map<Object, Object> alreadyChecked) {
    if (one == another) {
        return;// ww w.  ja  v  a2  s .com
    }
    if (one == null && another != null || one != null && another == null) {
        Assert.fail("One of both is null: " + one + ", " + another);
    }
    if (alreadyChecked.containsKey(one)) {
        return;
    }
    alreadyChecked.put(one, another);

    Assert.assertEquals(one.getClass(), another.getClass());
    if (one.getClass().isPrimitive() || one instanceof String || one instanceof Character
            || one instanceof Boolean) {
        Assert.assertEquals(one, another);
        return;
    }

    if (Map.class.isAssignableFrom(one.getClass())) {
        final Map<?, ?> m1 = (Map<?, ?>) one;
        final Map<?, ?> m2 = (Map<?, ?>) another;
        Assert.assertEquals(m1.size(), m2.size());
        for (final Map.Entry<?, ?> entry : m1.entrySet()) {
            assertDeepEquals(entry.getValue(), m2.get(entry.getKey()));
        }
        return;
    }

    if (Set.class.isAssignableFrom(one.getClass())) {
        final Set<?> m1 = (Set<?>) one;
        final Set<?> m2 = (Set<?>) another;
        Assert.assertEquals(m1.size(), m2.size());
        final Iterator<?> iter1 = m1.iterator();
        final Iterator<?> iter2 = m2.iterator();
        while (iter1.hasNext()) {
            assertDeepEquals(iter1.next(), iter2.next());
        }
        return;
    }

    if (Number.class.isAssignableFrom(one.getClass())) {
        Assert.assertEquals(((Number) one).longValue(), ((Number) another).longValue());
        return;
    }

    if (one instanceof Currency) {
        // Check that the transient field defaultFractionDigits is initialized correctly (that was issue #34)
        final Currency currency1 = (Currency) one;
        final Currency currency2 = (Currency) another;
        Assert.assertEquals(currency1.getCurrencyCode(), currency2.getCurrencyCode());
        Assert.assertEquals(currency1.getDefaultFractionDigits(), currency2.getDefaultFractionDigits());
    }

    Class<? extends Object> clazz = one.getClass();
    while (clazz != null) {
        assertEqualDeclaredFields(clazz, one, another, alreadyChecked);
        clazz = clazz.getSuperclass();
    }

}

From source file:Main.java

/**
 * Get a list of the name of variables of the class received
 * @param klass Class to get the variable names
 * @return List<String>[] of length 3 with variable names: [0]: primitives, [1]: arrays, [2]: objects
 *//*from w ww  .  j av  a  2s .c  o m*/
public static List<String>[] getVariableNames(Class klass) {

    //array to return
    List<String>[] varNames = new List[3];
    for (int i = 0; i < 3; i++) {
        varNames[i] = new ArrayList<>();
    }

    //add all valid fields
    do {
        Field[] fields = klass.getDeclaredFields();
        for (Field field : fields) {
            if (!Modifier.isTransient(field.getModifiers())) {

                //get the type
                Class type = field.getType();

                if (type.isPrimitive() || (type == Integer.class) || (type == Float.class)
                        || (type == Double.class) || (type == Boolean.class) || (type == String.class)) {
                    varNames[0].add(field.getName());
                } else if (type.isArray()) {
                    varNames[1].add(field.getName());
                } else {
                    varNames[2].add(field.getName());
                }
            }
        }

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

    //return array
    return varNames;

}

From source file:com.google.gwtjsonrpc.server.JsonServlet.java

@SuppressWarnings("unchecked")
private static Class<? extends RemoteJsonService> findInterface(Class<?> c) {
    while (c != null) {
        if (c.isInterface() && RemoteJsonService.class.isAssignableFrom(c)) {
            return (Class<RemoteJsonService>) c;
        }/*from ww w  . j  av  a 2  s.c om*/
        for (final Class<?> i : c.getInterfaces()) {
            final Class<? extends RemoteJsonService> r = findInterface(i);
            if (r != null) {
                return r;
            }
        }
        c = c.getSuperclass();
    }
    return null;
}

From source file:me.xiaopan.android.gohttp.requestobject.RequestParser.java

/**
 * ?//from   ww  w  .  j a  v  a2  s.  c  o m
 * @param sourceClass 
 * @param isAddCurrentClass ??
 * @return 
 */
private static List<Class<?>> getSuperClasses(Class<?> sourceClass, boolean isAddCurrentClass) {
    List<Class<?>> classList = new ArrayList<Class<?>>();
    Class<?> currentClass;
    if (isAddCurrentClass) {
        currentClass = sourceClass;
    } else {
        currentClass = sourceClass.getSuperclass();
    }
    while (currentClass != null) {
        classList.add(currentClass);
        currentClass = currentClass.getSuperclass();
    }
    return classList;
}

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

public static Field findField(Object target, String fieldName) {
    Class<?> targetClass = getClass(target);
    Field theField;//from  w  w w.j a  v  a 2 s .c  o m
    try {
        theField = targetClass.getDeclaredField(fieldName);
        return setAccess(theField);
    } catch (NoSuchFieldException e) {
        if (targetClass.getSuperclass() != null)
            return findField(targetClass.getSuperclass(), fieldName);
        else
            return null;
    }
}

From source file:edu.usu.sdl.openstorefront.validation.ValidationUtil.java

private static List<RuleResult> validateFields(final ValidationModel validateModel, Class dataClass,
        String parentFieldName, String parentType) {
    List<RuleResult> ruleResults = new ArrayList<>();

    if (validateModel.getDataObject() == null && validateModel.isAcceptNull() == false) {
        RuleResult validationResult = new RuleResult();
        validationResult.setMessage("The whole data object is null.");
        validationResult.setValidationRule("Don't allow null object");
        validationResult.setEntityClassName(parentType);
        validationResult.setFieldName(parentFieldName);
        ruleResults.add(validationResult);
    } else {/* w  w  w.j a  v a  2  s .  c  o  m*/
        if (validateModel.getDataObject() != null) {
            if (dataClass.getSuperclass() != null) {
                ruleResults.addAll(validateFields(validateModel, dataClass.getSuperclass(), null, null));
            }

            for (Field field : dataClass.getDeclaredFields()) {
                Class fieldClass = field.getType();
                boolean process = true;
                if (validateModel.isConsumeFieldsOnly()) {
                    ConsumeField consumeField = (ConsumeField) field.getAnnotation(ConsumeField.class);
                    if (consumeField == null) {
                        process = false;
                    }
                }

                if (process) {
                    if (ReflectionUtil.isComplexClass(fieldClass)) {
                        //composition class
                        if (Logger.class.getName().equals(fieldClass.getName()) == false
                                && fieldClass.isEnum() == false) {
                            try {
                                Method method = validateModel.getDataObject().getClass().getMethod(
                                        "get" + StringUtils.capitalize(field.getName()), (Class<?>[]) null);
                                Object returnObj = method.invoke(validateModel.getDataObject(),
                                        (Object[]) null);
                                boolean check = true;
                                if (returnObj == null) {
                                    NotNull notNull = (NotNull) fieldClass.getAnnotation(NotNull.class);
                                    if (notNull == null) {
                                        check = false;
                                    }
                                }
                                if (check) {
                                    ruleResults.addAll(
                                            validateFields(ValidationModel.copy(validateModel, returnObj),
                                                    fieldClass, field.getName(),
                                                    validateModel.getDataObject().getClass().getSimpleName()));
                                }
                            } catch (NoSuchMethodException | SecurityException | IllegalAccessException
                                    | IllegalArgumentException | InvocationTargetException ex) {
                                throw new OpenStorefrontRuntimeException(ex);
                            }
                        }
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(List.class.getSimpleName())
                            || fieldClass.getSimpleName().equalsIgnoreCase(Map.class.getSimpleName())
                            || fieldClass.getSimpleName().equalsIgnoreCase(Collection.class.getSimpleName())
                            || fieldClass.getSimpleName().equalsIgnoreCase(Set.class.getSimpleName())) {
                        //multi
                        if (fieldClass.getSimpleName().equalsIgnoreCase(Map.class.getSimpleName())) {
                            try {
                                Method method = validateModel.getDataObject().getClass().getMethod(
                                        "get" + StringUtils.capitalize(field.getName()), (Class<?>[]) null);
                                Object returnObj = method.invoke(validateModel.getDataObject(),
                                        (Object[]) null);
                                Map mapObj = (Map) returnObj;
                                for (Object entryObj : mapObj.entrySet()) {
                                    ruleResults.addAll(
                                            validateFields(ValidationModel.copy(validateModel, entryObj),
                                                    entryObj.getClass(), field.getName(),
                                                    validateModel.getDataObject().getClass().getSimpleName()));
                                }
                            } catch (NoSuchMethodException | SecurityException | IllegalAccessException
                                    | IllegalArgumentException | InvocationTargetException ex) {
                                throw new OpenStorefrontRuntimeException(ex);
                            }
                        } else {
                            try {
                                Method method = validateModel.getDataObject().getClass().getMethod(
                                        "get" + StringUtils.capitalize(field.getName()), (Class<?>[]) null);
                                Object returnObj = method.invoke(validateModel.getDataObject(),
                                        (Object[]) null);
                                if (returnObj != null) {
                                    for (Object itemObj : (Collection) returnObj) {
                                        if (itemObj != null) {
                                            ruleResults.addAll(validateFields(
                                                    ValidationModel.copy(validateModel, itemObj),
                                                    itemObj.getClass(), field.getName(),
                                                    validateModel.getDataObject().getClass().getSimpleName()));
                                        } else {
                                            log.log(Level.WARNING,
                                                    "There is a NULL item in a collection.  Check data passed in to validation.");
                                        }
                                    }
                                } else {
                                    NotNull notNull = field.getAnnotation(NotNull.class);
                                    if (notNull != null) {
                                        RuleResult ruleResult = new RuleResult();
                                        ruleResult.setMessage("Collection is required");
                                        ruleResult.setEntityClassName(
                                                validateModel.getDataObject().getClass().getSimpleName());
                                        ruleResult.setFieldName(field.getName());
                                        ruleResult.setValidationRule("Requires value");
                                        ruleResults.add(ruleResult);
                                    }
                                }
                            } catch (NoSuchMethodException | SecurityException | IllegalAccessException
                                    | IllegalArgumentException | InvocationTargetException ex) {
                                throw new OpenStorefrontRuntimeException(ex);
                            }
                        }

                    } else {
                        //simple case
                        for (BaseRule rule : rules) {
                            //Stanize if requested
                            if (validateModel.getSantize()) {
                                Sanitize santize = field.getAnnotation(Sanitize.class);
                                if (santize != null) {
                                    try {
                                        Sanitizer santizer = santize.value().newInstance();

                                        Method method = dataClass.getMethod(
                                                "get" + StringUtils.capitalize(field.getName()),
                                                (Class<?>[]) null);
                                        Object returnObj = method.invoke(validateModel.getDataObject(),
                                                (Object[]) null);

                                        Object newValue = santizer.santize(returnObj);

                                        method = dataClass.getMethod(
                                                "set" + StringUtils.capitalize(field.getName()), String.class);
                                        method.invoke(validateModel.getDataObject(), newValue);

                                    } catch (InstantiationException | IllegalAccessException
                                            | NoSuchMethodException | SecurityException
                                            | InvocationTargetException ex) {
                                        throw new OpenStorefrontRuntimeException(ex);
                                    }
                                }
                            }

                            RuleResult validationResult = rule.processField(field,
                                    validateModel.getDataObject());
                            if (validationResult != null) {
                                ruleResults.add(validationResult);
                            }
                        }
                    }
                }
            }
        }
    }

    return ruleResults;
}