If i don't know the class type, is not much easier (and faster) try to cast the object instead of invoking methods in that way?
Why (and when) i should use this way?
I assume you mean "If I know" not "If I don't know" above.
If you have com.mkyong.reflection.AppTest
at compile-time, then you wouldn't need to use reflection to use it at all. Just use it:
// In your imports section (although you don't *have* to do this,
// it's normal practice to avoid typing com.mkyong.reflection.AppTest
// everywhere you use it)
import com.mkyong.reflection.AppTest;
// ...and then later in a method...
//load the AppTest at runtime
AppTest obj = new AppTest();
//call the printIt method
obj.printIt();
If you don't know the class at compile-time, you can't cast the result of newInstance
to it, because...you don't have it at compile time.
A common middle ground is interfaces. If com.mkyong.reflection.AppTest
implements an interface (say, TheInterface
), then you could do this:
//load the AppTest at runtime
Class cls = Class.forName("com.mkyong.reflection.AppTest");
TheInterface obj = (TheInterface)cls.newInstance();
//call the printIt method
obj.printIt();
At compile-time, all you need is the interface, not the implementing class. You can load the implementing class at runtime. This is a fairly common pattern for plugins (like, say, JDBC implementations).