Annotations - find all annotated parents

This commit is contained in:
Emmanuel BENOîT 2015-09-14 08:43:29 +02:00
parent 5b3d927aae
commit 604967af9c
2 changed files with 38 additions and 0 deletions

View file

@ -197,4 +197,26 @@ public final class Annotations
return found;
}
public static < T > ArrayList< Class< ? super T > > findParentsWith( final Class< T > klass ,
final Class< ? extends Annotation > annotation )
{
ArrayList< Class< ? super T > > output = new ArrayList< >( );
findParentsWith( output , klass , annotation );
return output;
}
public static < T > void findParentsWith( ArrayList< Class< ? super T > > output , Class< T > klass ,
Class< ? extends Annotation > annotation )
{
Class< ? super T > current = klass;
while ( current != null ) {
if ( current.getDeclaredAnnotation( annotation ) != null ) {
output.add( current );
}
current = current.getSuperclass( );
}
}
}

View file

@ -169,4 +169,20 @@ public class TestAnnotations
{
Assert.assertSame( CTest1.class , Annotations.findFarthestClass( CTest4.class , ATest3.class ) );
}
/**
* Test: {@link Annotations#findParentsWith(Class, Class)}
*/
@Test
public void testFindParentsWith( )
{
ArrayList< Class< ? super CTest4 > > result = Annotations.findParentsWith( CTest4.class , ATest1.class );
Assert.assertEquals( 2 , result.size( ) );
Assert.assertSame( CTest3.class , result.get( 0 ) );
Assert.assertSame( CTest2.class , result.get( 1 ) );
result = Annotations.findParentsWith( CTest4.class , ATest2.class );
Assert.assertTrue( result.isEmpty( ) );
}
}