File tree Expand file tree Collapse file tree
main/java/com/baeldung/casting
test/java/com/baeldung/casting Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .baeldung .casting ;
2+
3+ import java .util .ArrayList ;
4+ import java .util .List ;
5+
6+ public class AnimalFeederGeneric <T > {
7+ private Class <T > type ;
8+
9+ public AnimalFeederGeneric (Class <T > type ) {
10+ this .type = type ;
11+ }
12+
13+ public List <T > feed (List <Animal > animals ) {
14+ List <T > list = new ArrayList <T >();
15+ animals .forEach (animal -> {
16+ if (type .isInstance (animal )) {
17+ T objAsType = type .cast (animal );
18+ list .add (objAsType );
19+ }
20+ });
21+ return list ;
22+ }
23+
24+ }
Original file line number Diff line number Diff line change @@ -11,6 +11,7 @@ public class CastingTest {
1111 public void whenPrimitiveConverted_thenValueChanged () {
1212 double myDouble = 1.1 ;
1313 int myInt = (int ) myDouble ;
14+
1415 assertNotEquals (myDouble , myInt );
1516 }
1617
@@ -55,4 +56,25 @@ public void whenDownCastWithoutCheck_thenExceptionThrown() {
5556 animals .add (new Dog ());
5657 new AnimalFeeder ().uncheckedFeed (animals );
5758 }
59+
60+ @ Test
61+ public void whenDowncastToCatWithCastMethod_thenMeowIsCalled () {
62+ Animal animal = new Cat ();
63+ if (Cat .class .isInstance (animal )) {
64+ Cat cat = Cat .class .cast (animal );
65+ cat .meow ();
66+ }
67+ }
68+
69+ @ Test
70+ public void whenParameterCat_thenOnlyCatsFed () {
71+ List <Animal > animals = new ArrayList <>();
72+ animals .add (new Cat ());
73+ animals .add (new Dog ());
74+ AnimalFeederGeneric <Cat > catFeeder = new AnimalFeederGeneric <Cat >(Cat .class );
75+ List <Cat > fedAnimals = catFeeder .feed (animals );
76+
77+ assertTrue (fedAnimals .size () == 1 );
78+ assertTrue (fedAnimals .get (0 ) instanceof Cat );
79+ }
5880}
You can’t perform that action at this time.
0 commit comments