Example usage for java.lang Class getDeclaredClasses

List of usage examples for java.lang Class getDeclaredClasses

Introduction

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

Prototype

@CallerSensitive
public Class<?>[] getDeclaredClasses() throws SecurityException 

Source Link

Document

Returns an array of Class objects reflecting all the classes and interfaces declared as members of the class represented by this Class object.

Usage

From source file:com.kildeen.visor.core.permission.PermissionResolverImpl.java

private PermissionModel createPermission(ConfigDescriptor<?> configDescriptor, Class<?> childClass,
        PermissionModel permissionParent) {
    Class<?> clazz = childClass;
    if (clazz == null) {
        //This is a root call and not a recursive call thus no child.
        clazz = configDescriptor.getConfigClass();
    }//from  ww w. j ava  2  s  .  c o  m
    Set<PermissionModel> children = new ListOrderedSet<>();
    if (mappingContext.isFolder(clazz)) {
        // Folder found, children needs to be created first
        for (Class<?> child : clazz.getDeclaredClasses()) {
            // Only add children if they are secured
            if (mappingContext.getMappedPermissions().containsKey(child)) {
                if (mappingContext.isFolder(child)) {
                    // This is the recursive part. The child is a folder thus needs to be created first. Important
                    // that it's ConfigDescriptor is used thus one strong reason for the mappingContext.
                    ConfigDescriptor descriptor = mappingContext.getMappedPermissions().get(child);
                    PermissionModel permission = createPermission(descriptor, child, permissionParent);
                    children.add(permission);
                    state.add(permission, false);

                } else {
                    // Child is not a folder.
                    ConfigDescriptor descriptor = mappingContext.getMappedPermissions().get(child);
                    PermissionModel model = createPermissionWithPartPermissions(descriptor, false);

                    children.add(model);
                    state.add(model, false);
                }
            }
        }
    } else {
        // Permission with no full worthy children. Might still have part permissions
        ConfigDescriptor viewDescriptor = mappingContext.getMappedPermissions().get(clazz);
        PermissionModel permission = createPermissionWithPartPermissions(viewDescriptor, true);
        return permission;
    }

    PermissionModel permission = new PermissionModelImpl(permissionConverter.getId(clazz), children,
            configDescriptor);
    // In a recursive call there's a parent
    if (permissionParent != null) {
        permissionParent.getChildren().add(permission);
        return permissionParent;
    }
    return permission;
}

From source file:com.spotify.docgenerator.DocgeneratorMojo.java

private Class<?> getClassForNameIsh(Sink sink, String className) {
    try {/*www.  j  ava 2  s  . co  m*/
        return getClassForName(className);
    } catch (ClassNotFoundException e) {
        final List<String> bits = Splitter.on(".").splitToList(className);
        final String childClassName = Joiner.on('.').join(bits.subList(0, bits.size() - 1));
        try {
            Class<?> clazz = getClassForName(childClassName);
            for (Class<?> clazzy : clazz.getDeclaredClasses()) {
                if (className.equals(clazzy.getCanonicalName())) {
                    return clazzy;
                }
            }
            return null;
        } catch (ClassNotFoundException e1) {
            sink.text(" -- can't find class");
            sink.lineBreak();
            return null;
        } catch (MalformedURLException e1) {
            sink.text(" -- inner url is hosed");
            sink.lineBreak();
            return null;
        }
    } catch (MalformedURLException e) {
        sink.text(" -- url is hosed");
        sink.lineBreak();
        return null;
    }
}

From source file:com.medigy.persist.model.data.EntitySeedDataPopulator.java

public void populateEntityCacheData() throws HibernateException {

    Iterator itr = null;/* w w  w  . j a v  a  2 s.  c om*/
    if (!useEjb)
        itr = configuration.getClassMappings();
    else
        itr = ejb3Configuration.getClassMappings();

    while (itr.hasNext()) {
        Class entityClass = ((PersistentClass) itr.next()).getMappedClass(); //(Class) classMappings.next();
        log.warn(entityClass.getName());
        if (!Entity.class.isAssignableFrom(entityClass))
            continue;

        Class[] innerClasses = entityClass.getDeclaredClasses();
        for (Class innerClass : innerClasses) {
            // TODO: assume that this is the inner CACHE class !???!!! maybe make Cache extend an interface to indicate this??
            if (innerClass.isEnum() && !entityClass.equals(Party.class)) {
                try {
                    final BeanInfo beanInfo = Introspector.getBeanInfo(entityClass);
                    final PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
                    final Hashtable pdsByName = new Hashtable();
                    for (int i = 0; i < descriptors.length; i++) {
                        final PropertyDescriptor descriptor = descriptors[i];
                        if (descriptor.getWriteMethod() != null)
                            pdsByName.put(descriptor.getReadMethod().getName(), descriptor.getWriteMethod());
                    }

                    Object[] enumObjects = innerClass.getEnumConstants();
                    // now match the enum methods with the enclosing class' methods
                    for (Object enumObj : enumObjects) {
                        Object entityObj = entityClass.newInstance();
                        final Method[] enumMethods = enumObj.getClass().getMethods();
                        for (Method enumMethod : enumMethods) {
                            final Method writeMethod = (Method) pdsByName.get(enumMethod.getName());
                            if (writeMethod != null) {
                                writeMethod.invoke(entityObj, enumMethod.invoke(enumObj));
                            }
                        }
                        HibernateUtil.getSession().save(entityObj);
                    }
                } catch (IntrospectionException e) {
                    log.error(e);
                } catch (IllegalAccessException e) {
                    log.error(e);
                } catch (InstantiationException e) {
                    log.error(e);
                } catch (InvocationTargetException e) {
                    log.error(e);
                } catch (HibernateException e) {
                    log.error(e);
                }
            }
        }
    }
}

From source file:org.romaframework.core.schema.SchemaHelper.java

/**
 * Return the generic type if iType uses Java5+ Generics.
 * //from  w  w w.  j  a  v a2  s .c o m
 * @param iType
 *          Type with generics
 * @return Generic Class<?> if any
 */
public static Class<?> getGenericClass(Type iType) {
    // CHECK IF IT'S A PARAMETIZERED TYPE
    if (!(iType instanceof ParameterizedType)) {
        return null;
    }

    Class<?> returnClass = null;

    // list the raw type information
    ParameterizedType ptype = (ParameterizedType) iType;
    Type rtype = ptype.getRawType();

    if (!(rtype instanceof Class<?>)) {
        // NO CLASS: RETURN NULL
        return null;
    }

    Type[] targs = ptype.getActualTypeArguments();

    if (targs == null || targs.length == 0) {
        return null;
    }

    Class<?> classType = (Class<?>) rtype;

    try {
        if (classType.isArray()) {
            returnClass = (Class<?>) targs[0];
        } else if (java.util.Collection.class.isAssignableFrom((Class<?>) rtype)) {
            returnClass = resolveClassFromType(targs[0], null);
            if (returnClass == null)
                returnClass = Object.class;

        } else if (java.util.Map.class.isAssignableFrom((Class<?>) rtype)) {
            returnClass = classType.getDeclaredClasses()[0];
        } else if (targs[0] instanceof Class<?>) {
            return (Class<?>) targs[0];
        }
    } catch (ClassCastException e) {
        throw new ConfigurationException(
                "Cannot determine embedded type for " + iType + ". Embedded class not found", e);
    }

    return returnClass;
}

From source file:se.crisp.codekvast.agent.daemon.codebase.CodeBaseScanner.java

void findTrackedConstructors(CodeBase codeBase, Class<?> clazz) {
    if (clazz.isInterface()) {
        log.debug("Ignoring interface {}", clazz);
        return;// w w  w .j ava  2s  .  co m
    }

    log.debug("Analyzing {}", clazz);
    MethodAnalyzer methodAnalyzer = codeBase.getConfig().getMethodAnalyzer();
    try {
        Constructor[] declaredConstructors = clazz.getDeclaredConstructors();

        for (Constructor constructor : declaredConstructors) {
            SignatureStatus status = methodAnalyzer.apply(constructor);
            MethodSignature thisSignature = SignatureUtils.makeConstructorSignature(clazz, constructor);
            codeBase.addSignature(thisSignature, thisSignature, status);
        }

        for (Class<?> innerClass : clazz.getDeclaredClasses()) {
            findTrackedConstructors(codeBase, innerClass);
        }
    } catch (NoClassDefFoundError e) {
        log.warn("Cannot analyze {}: {}", clazz, e.toString());
    }
}

From source file:org.eclipse.gemini.blueprint.test.AbstractOnTheFlyBundleCreatorTests.java

/**
 * Determine imports for the given bundle. Based on the user settings, this
 * method will consider only the the test hierarchy until the testing
 * framework is found or all classes available inside the test bundle. <p/>
 * Note that split packages are not supported.
 * //  w ww . ja v a2  s . c o  m
 * @return
 */
private String[] determineImports() {

    boolean useTestClassOnly = false;

    // no jar entry present, bail out.
    if (jarEntries == null || jarEntries.isEmpty()) {
        logger.debug("No test jar content detected, generating bundle imports from the test class");
        useTestClassOnly = true;
    }

    else if (createManifestOnlyFromTestClass()) {
        logger.info("Using the test class for generating bundle imports");
        useTestClassOnly = true;
    } else
        logger.info("Using all classes in the jar for the generation of bundle imports");

    // className, class resource
    Map entries;

    if (useTestClassOnly) {

        entries = new LinkedHashMap(4);

        // get current class (test class that bootstraps the OSGi infrastructure)
        Class<?> clazz = getClass();
        String clazzPackage = null;
        String endPackage = AbstractOnTheFlyBundleCreatorTests.class.getPackage().getName();

        do {

            // consider inner classes as well
            List classes = new ArrayList(4);
            classes.add(clazz);
            CollectionUtils.mergeArrayIntoCollection(clazz.getDeclaredClasses(), classes);

            for (Iterator iterator = classes.iterator(); iterator.hasNext();) {
                Class<?> classToInspect = (Class) iterator.next();

                Package pkg = classToInspect.getPackage();
                if (pkg != null) {
                    clazzPackage = pkg.getName();
                    String classFile = ClassUtils.getClassFileName(classToInspect);
                    entries.put(classToInspect.getName().replace('.', '/').concat(ClassUtils.CLASS_FILE_SUFFIX),
                            new InputStreamResource(classToInspect.getResourceAsStream(classFile)));
                }
                // handle default package
                else {
                    logger.warn("Could not find package for class " + classToInspect + "; ignoring...");
                }
            }

            clazz = clazz.getSuperclass();

        } while (!endPackage.equals(clazzPackage));
    } else
        entries = jarEntries;

    return determineImportsFor(entries);

}

From source file:org.eclipse.emf.mwe.utils.StandaloneSetup.java

/**
 * Adds an extension//w ww  . j  a  v a  2  s .c  o m
 * 
 * @param m
 *            <tt>from</tt>: extension name, <tt>to</tt> factory classname
 * @throws ConfigurationException
 *             <ul>
 *             <li>The factory class for the extension cannot be found
 *             <li>The inner factory class for the extension cannot be found
 *             </ul>
 */
public void addExtensionMap(final Mapping m) throws ConfigurationException {
    log.info("Adding Extension mapping from '" + m.getFrom() + "' to '" + m.getTo() + "'");
    try {
        // locate the factory class of the extension
        Class<?> factoryClass = ResourceLoaderFactory.createResourceLoader().loadClass(m.getTo());
        if (factoryClass == null)
            throw new ConfigurationException(
                    "cannot find class " + m.getTo() + " for extension " + m.getFrom());
        Object factoryInstance = null;
        if (factoryClass.isInterface()) {
            final Class<?>[] innerClasses = factoryClass.getDeclaredClasses();
            factoryClass = null;
            for (int j = 0; j < innerClasses.length; j++) {
                if (Resource.Factory.class.isAssignableFrom(innerClasses[j])) {
                    factoryClass = innerClasses[j];
                }
            }
            if (factoryClass == null)
                throw new ConfigurationException(
                        "cannot find inner factory class " + m.getTo() + " for extension " + m.getFrom());
            final Field instanceField = factoryClass.getField("INSTANCE");
            factoryInstance = instanceField.get(null);
        } else {
            factoryInstance = factoryClass.newInstance();
        }
        Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(m.getFrom(), factoryInstance);
    } catch (final Exception e) {
        throw new ConfigurationException(e);
    }
}

From source file:org.neo4j.consistency.checking.full.FullCheckIntegrationTest.java

@BeforeClass
public static void collectAllDifferentInconsistencyTypes() {
    Class<?> reportClass = ConsistencyReport.class;
    for (Class<?> cls : reportClass.getDeclaredClasses()) {
        for (Method method : cls.getDeclaredMethods()) {
            if (method.getAnnotation(Documented.class) != null) {
                Set<String> types = allReports.get(cls);
                if (types == null) {
                    allReports.put(cls, types = new HashSet<>());
                }/*from  www .  j  a  va2s .  c  om*/
                types.add(method.getName());
            }
        }
    }
}

From source file:tk.eatheat.omnisnitch.ui.SwitchLayout.java

@SuppressWarnings("rawtypes")
public SwitchLayout(Context context) {
    mContext = context;// ww  w.j av  a  2s  . com
    mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
    mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
    mConfiguration = SwitchConfiguration.getInstance(mContext);

    mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mLoadedTasks = new ArrayList<TaskDescription>();
    mRecentListAdapter = new RecentListAdapter(mContext, android.R.layout.simple_list_item_multiple_choice,
            mLoadedTasks);
    mFavoriteList = new ArrayList<String>();
    mFavoriteListAdapter = new FavoriteListAdapter(mContext, android.R.layout.simple_list_item_multiple_choice,
            mFavoriteList);

    final ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
    am.getMemoryInfo(mMemInfo);
    String sClassName = "android.app.ActivityManager";
    try {
        Class classToInvestigate = Class.forName(sClassName);
        Class[] classes = classToInvestigate.getDeclaredClasses();
        for (int i = 0; i < classes.length; i++) {
            Class c = classes[i];
            if (c.getName().equals("android.app.ActivityManager$MemoryInfo")) {
                String strNewFieldName = "secondaryServerThreshold";
                Field field = c.getField(strNewFieldName);
                mSecServerMem = field.getLong(mMemInfo);
                break;
            }
        }
    } catch (ClassNotFoundException e) {
    } catch (NoSuchFieldException e) {
    } catch (Exception e) {
    }
}

From source file:org.lockss.test.LockssTestCase.java

/**
 * <p>Returns a test suite with the combined tests in all the
 * nested classes found in <code>thisClass</code> that extend
 * the <code>extendedClass</code> class.</p>
 * <p>Typically this will lead to the parameters being
 * <code>(myTestCase, myTestCase)</code> or
 * <code>(myTestCase, myTesterClass)</code>.</p>
 * @param thisClass     The class whose variant nested classes are
 *                      being extracted by reflection.
 * @param extendedClass The class that variant classes have to extend
 *                      in order to be extracted by reflection.
 * @return A test suite incorporating the tests of all the extracted
 *         nested classes.//  w  w w  .  j  a  v a2s.c  o  m
 * @see #variantSuites(Class[])
 */
public static Test variantSuites(Class thisClass, Class extendedClass) {
    ArrayList list = new ArrayList();
    for (Iterator iter = new ObjectArrayIterator(thisClass.getDeclaredClasses()); iter.hasNext();) {
        Class cla = (Class) iter.next();
        if (extendedClass.isAssignableFrom(cla)) {
            list.add(cla);
        }
    }

    Class[] classes = new Class[list.size()];
    list.toArray(classes);
    return variantSuites(classes);
}