views:

55

answers:

3

hi, i load a class using

Class.forName(klassname,false,loader)

After this i create an instance using

klass.newInstance(); It returns an object type.I want to cast it to specific type(ie.Klassnamw instance).I used normal casting but it gets hung because it is not resolved during runtime.How can i cast it?Hellp

+3  A: 

Casting is usually used to give the compiler more information. You don't have that information at compile-time, so you can't give it to the compiler.

Moreover, the point of casting is usually so that you can get to some member of the class which wouldn't be known otherwise - but if you don't know the class until execution time, how can you know the members?

There are certain cases where it would be nice, but they're pretty uncommon. What are you trying to do with the instance after you've created it? If you're trying to call methods which you do know about at compile time, can you make those methods part of an interface and cast to the interface?

Jon Skeet
Thanks for reply.Yes i will call some methods which i know.I will try with interface.Actually i need it for hibernate framework. I want an instance of session. I am trying to do it by loading Configuration and create its instance .After that i create sessionfactory and then session.I am struck at first part itself
Steven
@Steven: You should be able to cast to Configuration, SessionFactory, or Session, no?
Thilo
thanks i got what you both were saying
Steven
A: 

You are using reflection because you do not know (or cannot resolve) the class to be loaded at compile time.

As such, you cannot cast to the class.

Unless there is an interface (or parent class) that you can resolve at compile-time (and thus cast to), you have to use reflection to do anything useful with the object.

Thilo
yes thanks got it
Steven
A: 

I've tried to dynaically load an object and then cast it to an interface but I get an

java.lang.Class cannot be cast to com.myclass....

error. What am I doing wrong?

Jake