Classes - Utilities to work with class hierarchies

This commit is contained in:
Emmanuel BENOîT 2015-09-15 08:58:37 +02:00
parent 604967af9c
commit 48252c20b5
4 changed files with 197 additions and 0 deletions
src/main/java/info/ebenoit/ebul/reflection

View file

@ -0,0 +1,80 @@
package info.ebenoit.ebul.reflection;
import java.util.ArrayList;
import java.util.HashSet;
/**
* Utility methods to query classes and interfaces.
*
* @author <a href="mailto:ebenoit@ebenoit.info">E. Benoît</a>
*/
public final class Classes
{
/**
* List all classes a class inherits from.
*
* @param cls
* the class to examine
* @return the list of ancestors, including the class itself
*/
public static < T > ArrayList< Class< ? super T > > getAncestors( final Class< T > cls )
{
final ArrayList< Class< ? super T > > result = new ArrayList< >( );
Class< ? super T > current = cls;
while ( current != null ) {
result.add( current );
current = current.getSuperclass( );
}
return result;
}
/**
* Find all types a class is compatible with: itself, its ancestors, and all implemented interfaces.
*
* @param cls
* the class to examine
* @return the set of compatible types
*/
public static HashSet< Class< ? > > getAllTypes( final Class< ? > cls )
{
final HashSet< Class< ? > > found = new HashSet< >( );
Class< ? > current = cls;
while ( current != null ) {
found.add( current );
Classes.addInterfaces( current , found );
current = current.getSuperclass( );
}
return found;
}
/**
* Internal method used by {@link #getAllTypes(Class)} to add all interfaces recursively.
*
* @param current
* the class or interface being examined
* @param found
* the result
*/
private static void addInterfaces( final Class< ? > current , final HashSet< Class< ? > > found )
{
if ( current == null ) {
return;
}
final Class< ? >[] interfaces = current.getInterfaces( );
final int len = interfaces.length;
for ( int i = 0 ; i < len ; i++ ) {
final Class< ? > itf = interfaces[ i ];
if ( found.add( itf ) ) {
Classes.addInterfaces( itf , found );
}
}
}
}