3

I'm following a java tutorial, i find this piece of code:

//load the AppTest at runtime
Class cls = Class.forName("com.mkyong.reflection.AppTest");
Object obj = cls.newInstance();

//call the printIt method
Method method = cls.getDeclaredMethod("printIt", noparams);
method.invoke(obj, null);

My question is: 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?

bebeto123
  • 230
  • 1
  • 2
  • 10

3 Answers3

2

Read this question What is reflection and why is it useful?

It says:

"For example, say you have an object of an unknown type in Java, and you would like
to call a 'doSomething' method on it if one exists
. Java's static typing system
isn't really designed to support this unless the object conforms to a known
interface, but using reflection, your code can look at the object and find out if
it has a method called 'doSomething' and then call it if you want to."

You can find a good tutotial here http://tutorials.jenkov.com/java-reflection/index.html

Community
  • 1
  • 1
Azincourt
  • 935
  • 5
  • 13
  • 29
0

One reason of doing it this way, not sure if in your case:

Method method = cls.getDeclaredMethod("printIt", noparams);
method.invoke(obj, null);

will allow u to call printIt even if it is private.

But if you cast to your class object then u will not be able to call private methods.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
0

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).

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875