* BAEL-1604

* BAEL-1604
This commit is contained in:
myluckagain 2018-03-05 16:21:48 +03:00 committed by Grzegorz Piwowarek
parent 029e160156
commit 103e6b69fa
2 changed files with 46 additions and 0 deletions

View File

@ -0,0 +1,24 @@
package com.baeldung.casting;
import java.util.ArrayList;
import java.util.List;
public class AnimalFeederGeneric<T> {
private Class<T> type;
public AnimalFeederGeneric(Class<T> type) {
this.type = type;
}
public List<T> feed(List<Animal> animals) {
List<T> list = new ArrayList<T>();
animals.forEach(animal -> {
if (type.isInstance(animal)) {
T objAsType = type.cast(animal);
list.add(objAsType);
}
});
return list;
}
}

View File

@ -11,6 +11,7 @@ public class CastingTest {
public void whenPrimitiveConverted_thenValueChanged() {
double myDouble = 1.1;
int myInt = (int) myDouble;
assertNotEquals(myDouble, myInt);
}
@ -55,4 +56,25 @@ public class CastingTest {
animals.add(new Dog());
new AnimalFeeder().uncheckedFeed(animals);
}
@Test
public void whenDowncastToCatWithCastMethod_thenMeowIsCalled() {
Animal animal = new Cat();
if (Cat.class.isInstance(animal)) {
Cat cat = Cat.class.cast(animal);
cat.meow();
}
}
@Test
public void whenParameterCat_thenOnlyCatsFed() {
List<Animal> animals = new ArrayList<>();
animals.add(new Cat());
animals.add(new Dog());
AnimalFeederGeneric<Cat> catFeeder = new AnimalFeederGeneric<Cat>(Cat.class);
List<Cat> fedAnimals = catFeeder.feed(animals);
assertTrue(fedAnimals.size() == 1);
assertTrue(fedAnimals.get(0) instanceof Cat);
}
}