sandejai
sandejai

Reputation: 989

Java: How can I type cast to a "Runtime" Class?

Code snippet :

private List<Animals> createAnimanlsIstance(Class cls) {
   Class typeCastedObject  =   (cls)getObjectBySomeCalculation();

}

Lets Say, I pass the Class as Dog.class at run Time and I want to type cast to Dog class Object. How can I achieve this, My above code is just a sample, Of what I want.

It's not like :

 if( obj instanceOf ClassA)
 {
   Object = (ClassA)  obj;
  }

I will be passing an instance of Class as parameter, ex : Dog.class,Cat.class etc.

Upvotes: 3

Views: 610

Answers (3)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136062

try this

Class typeCastedObject = cls.cast(getObjectBySomeCalculation());

Upvotes: 0

sp00m
sp00m

Reputation: 48837

You could probably use generics:

private <T> List<Animal> createAnimalsInstances(Class<T> clazz) {
    T castedObject = (T) getObjectBySomeCalculation();    
}

If the casted objects are intended to be added into a List<Animal> (i.e. are extending Animal), then you'll need:

private <T extends Animal> List<Animal> createAnimalsInstances(Class<T> clazz) {
    T castedObject = (T) getObjectBySomeCalculation();    
}

Upvotes: 1

Martijn Courteaux
Martijn Courteaux

Reputation: 68887

You might try generics:

private <T> List<Animals> createAnimalsInstance(Class<T> cls)
{
    T typeCastedObject = (T) getObjectBySomeCalculation();

}

Then you can simply use this method as usual:

List<Animals> animals = createAnimalsInstance(Dog.class);

FYI: If you want to do instanceof you can use Class.isAssignableFrom:

if (obj instanceOf AClass)

is equivalent with

if (AClass.isAssignableFrom(obj.getClass()))

Upvotes: 1

Related Questions