简体   繁体   中英

Java iterate through a set of classes

I have the following code:

Reflections reflections = new Reflections("com.mypackage.cmds");
Set<Class<? extends Command>> commandClasses = reflections.getSubTypesOf(Command.class);

What it does is to store in a Set all classes descendant from Command class that are within the package com.mypackage.cmds.

Now what I want to do is to iterate or traverse through that returned set so each of those classes are loaded calling Class.fromName method. How can I achieve this?

Thanks a lot in advance,

You do it with a standard for-each loop:

for (Class clazz: commandClasses) {
    // operate on clazz
}

This works for any Collection that implements the Iterator interface.

you can do it like this :

Iterator i = commandClasses.iterator();
        while (i.hasNext()) {
            i.next(); //will return next object     
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM