Example usage for java.lang Class getGenericSuperclass

List of usage examples for java.lang Class getGenericSuperclass

Introduction

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

Prototype

public Type getGenericSuperclass() 

Source Link

Document

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

Usage

From source file:com.frank.search.solr.repository.support.SimpleSolrRepository.java

private ParameterizedType resolveReturnedClassFromGernericType(Class<?> clazz) {
    Object genericSuperclass = clazz.getGenericSuperclass();
    if (genericSuperclass instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
        Type rawtype = parameterizedType.getRawType();
        if (SimpleSolrRepository.class.equals(rawtype)) {
            return parameterizedType;
        }// w ww  . java2 s  .  co m
    }
    return resolveReturnedClassFromGernericType(clazz.getSuperclass());
}

From source file:com.iwancool.dsm.dao.impl.AbstractBaseGenericORMDaoImpl.java

@SuppressWarnings("rawtypes")
public Class getSuperClassGenricType(final Class clazz, final int index) {
    Type genType = clazz.getGenericSuperclass();
    if (!(genType instanceof ParameterizedType)) {
        return Object.class;
    }/*www  .j  a  va  2 s  .  c  o m*/
    Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
    if (index >= params.length || index < 0) {
        return Object.class;
    }
    if (!(params[index] instanceof Class)) {
        return Object.class;
    }
    return (Class) params[index];
}

From source file:com.lynn.dao.BaseDao.java

public BaseDao() {
    this.entityClass = null;
    Class<?> c = getClass();
    Type type = c.getGenericSuperclass();
    if (type instanceof ParameterizedType) {
        Type[] parameterizedType = ((ParameterizedType) type).getActualTypeArguments();
        this.entityClass = (Class<T>) parameterizedType[0];
    }/* w  ww . j ava  2s  . c  om*/
}

From source file:com.conversantmedia.mapreduce.tool.annotation.handler.MaraAnnotationUtil.java

protected Type[] getParentGenericTypeParams(Class<?> clazz) {
    Type genericType = clazz.getGenericSuperclass();
    if (genericType instanceof ParameterizedType) {
        return toRawTypes(((ParameterizedType) genericType).getActualTypeArguments());
    }/*from  w  w  w .j  av  a 2 s. c  o m*/
    return null;
}

From source file:GenericClass.java

private void recurse(Class<?> clazz) {
    Type supclass = clazz.getGenericSuperclass();
    Class simplesup = clazz.getSuperclass();
    if (supclass == null)
        return;//from w w w. j a  va2  s  .  co m
    if (supclass instanceof ParameterizedType) {
        recurse(clazz, simplesup, (ParameterizedType) supclass);
    } else {
        recurse(simplesup);
    }
}

From source file:org.kuali.rice.krad.uif.util.ObjectPropertyUtils.java

/**
 * Locate the generic type declaration for a given target class in the generic type hierarchy of
 * the source class.// w  w w  .  j ava  2 s. c o m
 * 
 * @param sourceClass The class representing the generic type hierarchy to scan.
 * @param targetClass The class representing the generic type declaration to locate within the
 *        source class' hierarchy.
 * @return The generic type representing the target class within the source class' generic
 *         hierarchy.
 */
public static Type findGenericType(Class<?> sourceClass, Class<?> targetClass) {
    if (!targetClass.isAssignableFrom(sourceClass)) {
        throw new IllegalArgumentException(targetClass + " is not assignable from " + sourceClass);
    }

    if (sourceClass.equals(targetClass)) {
        return sourceClass;
    }

    @SuppressWarnings("unchecked")
    Queue<Type> typeQueue = RecycleUtils.getInstance(LinkedList.class);
    typeQueue.offer(sourceClass);
    while (!typeQueue.isEmpty()) {
        Type type = typeQueue.poll();

        Class<?> upperBound = getUpperBound(type);
        if (targetClass.equals(upperBound)) {
            return type;
        }

        Type genericSuper = upperBound.getGenericSuperclass();
        if (genericSuper != null) {
            typeQueue.offer(genericSuper);
        }

        Type[] genericInterfaces = upperBound.getGenericInterfaces();
        for (int i = 0; i < genericInterfaces.length; i++) {
            if (genericInterfaces[i] != null) {
                typeQueue.offer(genericInterfaces[i]);
            }
        }
    }

    throw new IllegalStateException(targetClass + " is assignable from " + sourceClass
            + " but could not be found in the generic type hierarchy");
}

From source file:org.apache.pig.EvalFunc.java

public EvalFunc() {
    // Resolve concrete type for T of EvalFunc<T>
    // 1. Build map from type param to type for class hierarchy from current class to EvalFunc
    Map<TypeVariable<?>, Type> typesByTypeVariable = new HashMap<TypeVariable<?>, Type>();
    Class<?> cls = getClass();
    Type type = cls.getGenericSuperclass();
    cls = cls.getSuperclass();/*w  ww  . j  a v  a  2  s. co  m*/
    while (EvalFunc.class.isAssignableFrom(cls)) {
        TypeVariable<? extends Class<?>>[] typeParams = cls.getTypeParameters();
        if (type instanceof ParameterizedType) {
            ParameterizedType pType = (ParameterizedType) type;
            Type[] typeArgs = pType.getActualTypeArguments();
            for (int i = 0; i < typeParams.length; i++) {
                typesByTypeVariable.put(typeParams[i], typeArgs[i]);
            }
        }
        type = cls.getGenericSuperclass();
        cls = cls.getSuperclass();
    }

    // 2. Use type param to type map to determine concrete type of for T of EvalFunc<T>
    Type targetType = EvalFunc.class.getTypeParameters()[0];
    while (targetType != null && targetType instanceof TypeVariable) {
        targetType = typesByTypeVariable.get(targetType);
    }
    if (targetType == null || targetType instanceof GenericArrayType || targetType instanceof WildcardType) {
        throw new RuntimeException(String.format(
                "Failed to determine concrete type for type parameter T of EvalFunc<T> for derived class '%s'",
                getClass().getName()));
    }
    returnType = targetType;

    // Type check the initial, intermediate, and final functions
    if (this instanceof Algebraic) {
        Algebraic a = (Algebraic) this;

        String errMsg = "function of " + getClass().getName() + " is not of the expected type.";
        if (getReturnTypeFromSpec(new FuncSpec(a.getInitial())) != Tuple.class)
            throw new RuntimeException("Initial " + errMsg);
        if (getReturnTypeFromSpec(new FuncSpec(a.getIntermed())) != Tuple.class)
            throw new RuntimeException("Intermediate " + errMsg);
        if (!getReturnTypeFromSpec(new FuncSpec(a.getFinal())).equals(returnType))
            throw new RuntimeException("Final " + errMsg);
    }

}

From source file:org.openmrs.module.webservices.rest.web.DelegatingCrudResourceTest.java

/**
 * This test looks at all subclasses of DelegatingCrudResource, and test all {@link RepHandler}
 * methods to make sure they are all capable of running without exceptions. It also checks that
 *//*from  w w w.j  a va 2s .co  m*/
@SuppressWarnings("rawtypes")
@Test
@Ignore
public void testAllReprsentationDescriptions() throws Exception {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            true);
    //only match subclasses of BaseDelegatingResource
    provider.addIncludeFilter(new AssignableTypeFilter(BaseDelegatingResource.class));

    // scan in org.openmrs.module.webservices.rest.web.resource package 
    Set<BeanDefinition> components = provider
            .findCandidateComponents("org.openmrs.module.webservices.rest.web.resource");
    if (CollectionUtils.isEmpty(components))
        Assert.fail("Faile to load any resource classes");

    for (BeanDefinition component : components) {
        Class resourceClass = Class.forName(component.getBeanClassName());
        for (Method method : ReflectionUtils.getAllDeclaredMethods(resourceClass)) {
            ParameterizedType parameterizedType = (ParameterizedType) resourceClass.getGenericSuperclass();
            Class openmrsClass = (Class) parameterizedType.getActualTypeArguments()[0];
            //User Resource is special in that the Actual parameterized Type isn't a standard domain object, so we also
            //need to look up fields and methods from the org.openmrs.User class 
            boolean isUserResource = resourceClass.equals(UserResource1_8.class);
            List<Object> refDescriptions = new ArrayList<Object>();

            if (method.getName().equals("getRepresentationDescription")
                    && method.getDeclaringClass().equals(resourceClass)) {
                //get all the rep definitions for all representations
                refDescriptions
                        .add(method.invoke(resourceClass.newInstance(), new Object[] { Representation.REF }));
                refDescriptions.add(
                        method.invoke(resourceClass.newInstance(), new Object[] { Representation.DEFAULT }));
                refDescriptions
                        .add(method.invoke(resourceClass.newInstance(), new Object[] { Representation.FULL }));
            }

            for (Object value : refDescriptions) {
                if (value != null) {
                    DelegatingResourceDescription des = (DelegatingResourceDescription) value;
                    for (String key : des.getProperties().keySet()) {
                        if (!key.equals("uri") && !key.equals("display") && !key.equals("auditInfo")) {
                            boolean hasFieldOrPropertySetter = (ReflectionUtils.findField(openmrsClass,
                                    key) != null);
                            if (!hasFieldOrPropertySetter) {
                                hasFieldOrPropertySetter = hasSetterMethod(key, resourceClass);
                                if (!hasFieldOrPropertySetter && isUserResource)
                                    hasFieldOrPropertySetter = (ReflectionUtils.findField(User.class,
                                            key) != null);
                            }
                            if (!hasFieldOrPropertySetter)
                                hasFieldOrPropertySetter = hasSetterMethod(key, resourceClass);

                            //TODO replace this hacky way that we are using to check if there is a get method for a 
                            //collection that has no actual getter e.g activeIdentifers and activeAttributes for Patient
                            if (!hasFieldOrPropertySetter) {
                                hasFieldOrPropertySetter = (ReflectionUtils.findMethod(openmrsClass,
                                        "get" + StringUtils.capitalize(key)) != null);
                                if (!hasFieldOrPropertySetter && isUserResource)
                                    hasFieldOrPropertySetter = (ReflectionUtils.findMethod(User.class,
                                            "get" + StringUtils.capitalize(key)) != null);
                            }

                            if (!hasFieldOrPropertySetter)
                                hasFieldOrPropertySetter = isallowedMissingProperty(resourceClass, key);

                            Assert.assertTrue(
                                    "No property found for '" + key + "' for " + openmrsClass
                                            + " nor setter method on resource " + resourceClass,
                                    hasFieldOrPropertySetter);
                        }
                    }
                }
            }
        }
    }
}

From source file:com.mmj.app.biz.base.BaseDao.java

/**
 * ?/*from  w w  w .  j a  v  a  2 s  .  c om*/
 */
public BaseDao() {
    Class<?> c = getClass();
    Type type = c.getGenericSuperclass();
    if (type instanceof ParameterizedType) {
        Type[] parameterizedType = ((ParameterizedType) type).getActualTypeArguments();
        if (Argument.isEmptyArray(parameterizedType)) {
            throw new UnSupportBaseDaoException("init entityClass mapperClass failed!");
        }
        this.entityClass = (Class<T>) parameterizedType[0];
        this.mapperClass = (Class<M>) parameterizedType[1];
    } else {
        throw new UnSupportBaseDaoException(
                String.format("?%s??T", getClass().getSimpleName()));
    }
}

From source file:org.batoo.common.reflect.ReflectHelper.java

private static Class<?> getTypeImpl(Class<?> clazz, Class<?> originalType, String methodName,
        List<Type> arguments) {
    final Map<TypeVariable<?>, Type> typeMap = Maps.newHashMap();

    if (arguments.size() > 0) {
        final TypeVariable<?>[] typeParameters = clazz.getTypeParameters();
        for (int i = 0; i < typeParameters.length; i++) {
            typeMap.put(typeParameters[i], arguments.get(i));
        }/*w  w  w .j a v a2s  .c om*/
    }

    try {
        final Method m = clazz.getDeclaredMethod(methodName);

        final Type type = typeMap.get(m.getGenericReturnType());
        if (type != null) {
            return ReflectHelper.checkAndReturn(originalType, m, (Class<?>) type);
        }

        return ReflectHelper.checkAndReturn(originalType, m, m.getReturnType());
    } catch (final NoSuchMethodException e) {
        final List<Type> typeArguments = Lists.newArrayList();

        if (clazz.getGenericSuperclass() instanceof ParameterizedType) {
            final ParameterizedType parameterizedType = (ParameterizedType) clazz.getGenericSuperclass();

            for (final Type typeArgument : parameterizedType.getActualTypeArguments()) {
                if (typeArgument instanceof TypeVariable) {
                    typeArguments.add(typeMap.get(typeArgument));
                } else {
                    typeArguments.add(typeArgument);
                }
            }
        }

        final Class<?> superclass = clazz.getSuperclass();

        if (superclass == Object.class) {
            return originalType;
        }

        return ReflectHelper.getTypeImpl(superclass, originalType, methodName, typeArguments);
    }
}