Problem:
I want to create a generic function which will return me strogly typed object.
Function :
public <T > T GetPet(AnimalKingdom allAnimals,int id) {
return (T) allAnimals.getAnimalsManager().findAnimalById(id);
}
The above function will return a strongly typed object or throw error.
Usage :
GetPet<Tiger>(thisZoo,tigersId).Roar();
Coming from C# background. Googled for the same but was not able to find a solution, it seems that I need to pass the generic type in function for it to work.
How can the above scenario implemented in java.
In Java, you explicitly specify the type arguments of the generic method before the method name. For example:
Then to invoke:
Alternatively, you can use type inferencing:
By the way, your
getPetmethod is not very safe because there is no runtime check performed to ensure the object returned is actually an instance ofTiger. In fact, the Java compiler gives a warning on this line:The reason is because the cast to
(T)is unchecked due to type erasure.To strengthen your code, I suggest the following change:
Then to invoke:
The benefit of passing in the class object (
Tiger.class) is that:<T>(again via type inferencing).Class.castmethod. The Java compiler warning goes away, and type safety is restored. For example, iffindAnimalByIdmistakenly returns an instance of Bear when you expected Tiger, you will get aClassCastException.