Skip to content

Commit 103e6b6

Browse files
myluckagainpivovarit
authored andcommitted
Bael-1604 (eugenp#3765)
* BAEL-1604 * BAEL-1604
1 parent 029e160 commit 103e6b6

2 files changed

Lines changed: 46 additions & 0 deletions

File tree

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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+
}

‎core-java/src/test/java/com/baeldung/casting/CastingTest.java‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff 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
}

0 commit comments

Comments
 (0)