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:Main.java

/**
 * Utility method that creates a <code>UIDefaults.LazyValue</code> that
 * creates an <code>ImageIcon</code> <code>UIResource</code> for the
 * specified image file name. The image is loaded using
 * <code>getResourceAsStream</code>, starting with a call to that method
 * on the base class parameter. If it cannot be found, searching will
 * continue through the base class' inheritance hierarchy, up to and
 * including <code>rootClass</code>.
 *
 * @param baseClass the first class to use in searching for the resource
 * @param rootClass an ancestor of <code>baseClass</code> to finish the
 *                  search at/* w  w w .ja va 2 s  . c  om*/
 * @param imageFile the name of the file to be found
 * @return a lazy value that creates the <code>ImageIcon</code>
 *         <code>UIResource</code> for the image,
 *         or null if it cannot be found
 */
public static Object makeIcon(final Class<?> baseClass, final Class<?> rootClass, final String imageFile) {

    return new UIDefaults.LazyValue() {
        public Object createValue(UIDefaults table) {
            /* Copy resource into a byte array.  This is
             * necessary because several browsers consider
             * Class.getResource a security risk because it
             * can be used to load additional classes.
             * Class.getResourceAsStream just returns raw
             * bytes, which we can convert to an image.
             */
            byte[] buffer = java.security.AccessController
                    .doPrivileged(new java.security.PrivilegedAction<byte[]>() {
                        public byte[] run() {
                            try {
                                InputStream resource = null;
                                Class<?> srchClass = baseClass;

                                while (srchClass != null) {
                                    resource = srchClass.getResourceAsStream(imageFile);

                                    if (resource != null || srchClass == rootClass) {
                                        break;
                                    }

                                    srchClass = srchClass.getSuperclass();
                                }

                                if (resource == null) {
                                    return null;
                                }

                                BufferedInputStream in = new BufferedInputStream(resource);
                                ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
                                byte[] buffer = new byte[1024];
                                int n;
                                while ((n = in.read(buffer)) > 0) {
                                    out.write(buffer, 0, n);
                                }
                                in.close();
                                out.flush();
                                return out.toByteArray();
                            } catch (IOException ioe) {
                                System.err.println(ioe.toString());
                            }
                            return null;
                        }
                    });

            if (buffer == null) {
                return null;
            }
            if (buffer.length == 0) {
                System.err.println("warning: " + imageFile + " is zero-length");
                return null;
            }

            return new ImageIconUIResource(buffer);
        }
    };
}

From source file:com.blurengine.blur.framework.ticking.TickMethodsCache.java

/**
 * Loads and caches a {@link Class}/*from   www .  j  a  v  a 2s . co m*/
 *
 * @param clazz class to load and cache for future usage
 *
 * @return list of {@link TickMethod} represented the cached methods
 *
 * @throws IllegalArgumentException thrown if {@code clazz} is {@code Tickable.class}
 */
public static Collection<TickMethod> loadClass(@Nonnull Class<?> clazz) throws IllegalArgumentException {
    Preconditions.checkNotNull(clazz, "clazz cannot be null.");
    if (!LOADED_CLASSES.contains(clazz)) {

        Collection<TickMethod> tickMethods = CLASS_TICK_METHODS.get(clazz); // empty cache list, automatically updates

        { // Load superclasses first
            Class<?> superclass = clazz.getSuperclass();
            // No need for while loop as loadClass will end up reaching here if necessary.
            if (!superclass.equals(Object.class)) {
                tickMethods.addAll(loadClass(superclass));
            }
        }

        for (Method method : clazz.getDeclaredMethods()) {
            TickMethod tickMethod = getTickMethod(clazz, method);
            if (tickMethod != null) {
                tickMethods.add(tickMethod);
            } else {
                Tick tick = method.getDeclaredAnnotation(Tick.class);
                if (tick != null) {
                    try {
                        Preconditions.checkArgument(method.getParameterCount() <= 1,
                                "too many parameters in tick method " + method.getName() + ".");
                        if (method.getParameterCount() > 0) {
                            Preconditions.checkArgument(
                                    method.getParameterTypes()[0].isAssignableFrom(TickerTask.class),
                                    "Invalid parameter in tick method " + method.getName() + ".");
                        }
                        boolean passParams = method.getParameterCount() > 0;
                        // Tickables may be marked private for organisation.
                        method.setAccessible(true);

                        tickMethods.add(new TickMethod(method, passParams, tick));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        LOADED_CLASSES.add(clazz);
    }
    return Collections.unmodifiableCollection(CLASS_TICK_METHODS.get(clazz));
}

From source file:br.gov.frameworkdemoiselle.ldap.internal.ClazzUtils.java

/**
 * Build a array of super classes fields
 * /*w w w.j  a  v a 2s  .c o m*/
 * @return Array of Super Classes Fields
 */
public static Field[] getSuperClassesFields(Class<?> entryClass) {
    Field[] fieldArray = entryClass.getDeclaredFields();
    Class<?> superClazz = entryClass.getSuperclass();
    while (superClazz != null && !"java.lang.Object".equals(superClazz.getName())) {
        fieldArray = (Field[]) ArrayUtils.addAll(fieldArray, superClazz.getDeclaredFields());
        superClazz = superClazz.getSuperclass();
    }
    return fieldArray;
}

From source file:de.hasait.clap.impl.CLAPClassNode.java

private static <A extends Annotation> A findAnnotation(final Class<?> pClass, final Class<A> pAnnotationClass) {
    final LinkedList<Class<?>> queue = new LinkedList<Class<?>>();
    queue.add(pClass);//from  w  w  w  .  j  a v a  2s.c  o m
    while (!queue.isEmpty()) {
        final Class<?> clazz = queue.removeFirst();
        if (clazz != null) {
            final A result = clazz.getAnnotation(pAnnotationClass);
            if (result != null) {
                return result;
            }
            queue.add(clazz.getSuperclass());
            for (final Class<?> interfaze : clazz.getInterfaces()) {
                queue.add(interfaze);
            }
        }
    }
    return null;
}

From source file:fi.foyt.foursquare.api.JSONFieldParser.java

/**
 * Returns whether class is derived from FoursquareEntity interface
 * //from  w  w  w .j  a  v a  2 s .c  o  m
 * @param clazz class
 * @return whether class is derived from FoursquareEntity interface
 */
private static boolean isFoursquareEntity(Class<?> clazz) {
    for (Class<?> intrf : clazz.getInterfaces()) {
        if (intrf.equals(FoursquareEntity.class)) {
            return true;
        }
    }

    Class<?> superClass = clazz.getSuperclass();
    if (!superClass.equals(Object.class)) {
        return isFoursquareEntity(superClass);
    }

    return false;
}

From source file:com.dungnv.vfw5.base.utils.StringUtils.java

public static void trimString(Object obj, boolean isLower) {
    String oldData = "";
    String newData = "";
    try {/*from   w  w  w . j a  va2  s .c o  m*/
        if (obj != null) {
            Class escapeClass = obj.getClass();
            Field fields[] = escapeClass.getDeclaredFields();
            Field superFields[] = escapeClass.getSuperclass().getDeclaredFields();
            Field allField[] = new Field[fields.length + superFields.length];
            System.arraycopy(fields, 0, allField, 0, fields.length);
            System.arraycopy(superFields, 0, allField, fields.length, superFields.length);
            for (Field f : allField) {
                f.setAccessible(true);
                if (f.getType().equals(java.lang.String.class) && !Modifier.isFinal(f.getModifiers())) {
                    if (f.get(obj) != null) {
                        oldData = f.get(obj).toString();
                        newData = isLower ? oldData.trim().toLowerCase() : oldData.trim();
                        f.set(obj, newData);
                    }
                } else if (f.getType().isArray()) {
                    if (f.getType().getComponentType().equals(java.lang.String.class)) {
                        String[] tmpArr = (String[]) f.get(obj);
                        if (tmpArr != null) {
                            for (int i = 0; i < tmpArr.length; i++) {
                                tmpArr[i] = isLower ? tmpArr[i].trim().toLowerCase() : tmpArr[i].trim();
                            }
                            f.set(obj, tmpArr);
                        }
                    }
                } else if (f.get(obj) instanceof List) {
                    List<Object> tmpList = (List<Object>) f.get(obj);
                    for (int i = 0; i < tmpList.size(); i++) {
                        if (tmpList.get(i) instanceof java.lang.String) {
                            tmpList.set(i, isLower ? tmpList.get(i).toString().trim().toLowerCase()
                                    : tmpList.get(i).toString().trim());
                        }
                    }
                    f.set(obj, tmpList);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.github.dozermapper.core.util.MappingUtils.java

public static List<Class<?>> getSuperClassesAndInterfaces(Class<?> srcClass, BeanContainer beanContainer) {
    List<Class<?>> superClasses = new ArrayList<>();
    Class<?> realClass = getRealClass(srcClass, beanContainer);

    // Add all super classes first
    Class<?> superClass = getRealClass(realClass, beanContainer).getSuperclass();
    while (!isBaseClass(superClass)) {
        superClasses.add(superClass);/*from   w ww  . j  a  v a2  s  .com*/
        superClass = superClass.getSuperclass();
    }

    // Now add all interfaces of the passed in class and all it's super classes

    // Linked hash set so duplicated are not added but insertion order is kept
    LinkedHashSet<Class<?>> interfaces = new LinkedHashSet<>();

    interfaces.addAll(getInterfaceHierarchy(realClass, beanContainer));
    for (Class<?> clazz : superClasses) {
        interfaces.addAll(getInterfaceHierarchy(clazz, beanContainer));
    }

    superClasses.addAll(interfaces);
    return superClasses;
}

From source file:com.ery.ertc.estorm.util.ClassSize.java

/**
 * The estimate of the size of a class instance depends on whether the JVM uses 32 or 64 bit addresses, that is it depends on the size
 * of an object reference. It is a linear function of the size of a reference, e.g. 24 + 5*r where r is the size of a reference (usually
 * 4 or 8 bytes).//from   w  w  w.ja  v a2 s  . c o m
 * 
 * This method returns the coefficients of the linear function, e.g. {24, 5} in the above example.
 * 
 * @param cl
 *            A class whose instance size is to be estimated
 * @param debug
 *            debug flag
 * @return an array of 3 integers. The first integer is the size of the primitives, the second the number of arrays and the third the
 *         number of references.
 */
@SuppressWarnings("unchecked")
private static int[] getSizeCoefficients(Class cl, boolean debug) {
    int primitives = 0;
    int arrays = 0;
    // The number of references that a new object takes
    int references = nrOfRefsPerObj;
    int index = 0;

    for (; null != cl; cl = cl.getSuperclass()) {
        Field[] field = cl.getDeclaredFields();
        if (null != field) {
            for (Field aField : field) {
                if (Modifier.isStatic(aField.getModifiers()))
                    continue;
                Class fieldClass = aField.getType();
                if (fieldClass.isArray()) {
                    arrays++;
                    references++;
                } else if (!fieldClass.isPrimitive()) {
                    references++;
                } else {// Is simple primitive
                    String name = fieldClass.getName();

                    if (name.equals("int") || name.equals("I"))
                        primitives += Bytes.SIZEOF_INT;
                    else if (name.equals("long") || name.equals("J"))
                        primitives += Bytes.SIZEOF_LONG;
                    else if (name.equals("boolean") || name.equals("Z"))
                        primitives += Bytes.SIZEOF_BOOLEAN;
                    else if (name.equals("short") || name.equals("S"))
                        primitives += Bytes.SIZEOF_SHORT;
                    else if (name.equals("byte") || name.equals("B"))
                        primitives += Bytes.SIZEOF_BYTE;
                    else if (name.equals("char") || name.equals("C"))
                        primitives += Bytes.SIZEOF_CHAR;
                    else if (name.equals("float") || name.equals("F"))
                        primitives += Bytes.SIZEOF_FLOAT;
                    else if (name.equals("double") || name.equals("D"))
                        primitives += Bytes.SIZEOF_DOUBLE;
                }
                if (debug) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("" + index + " " + aField.getName() + " " + aField.getType());
                    }
                }
                index++;
            }
        }
    }
    return new int[] { primitives, arrays, references };
}

From source file:com.ndemyanovskyi.backend.site.Site.java

static void addIntoValues(Site site) {
    Class c = site.getClass();
    do {/*w w  w . java 2s . c om*/
        UnmodifiableSetWrapper values = VALUES.get(c);
        values.add(site);
    } while ((c = c.getSuperclass()) != Object.class);
}

From source file:com.oltpbenchmark.util.ClassUtil.java

/**
 * Return an ordered list of all the sub-classes for a given class
 * Useful when dealing with generics/*from  w  w  w.j av a 2s  . co  m*/
 * @param element_class
 * @return
 */
public static List<Class<?>> getSuperClasses(Class<?> element_class) {
    List<Class<?>> ret = ClassUtil.CACHE_getSuperClasses.get(element_class);
    if (ret == null) {
        ret = new ArrayList<Class<?>>();
        while (element_class != null) {
            ret.add(element_class);
            element_class = element_class.getSuperclass();
        } // WHILE
        ret = Collections.unmodifiableList(ret);
        ClassUtil.CACHE_getSuperClasses.put(element_class, ret);
    }
    return (ret);
}