parent
029e160156
commit
103e6b69fa
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue