Re: Reflection, how to understand
- From: jagonzal@xxxxxxxxx
- Date: 31 Aug 2006 11:45:00 -0700
John_Woo wrote:
Hi,
I'm trying understand jdk 5 reflection.
I know it's for loading/invoking method on the fly. I'm wondering, any
simple core-java example (not sort of EJB, rmi) illuestrated how an app
re-compile then invoke the newly classes/methods, and why need to do
that (recompile)?
AFAIK, it doesn't have to do with recompiling - it has to do with, as
you said, dynamically accessing to classes.
For example:
String classname = "org.some.class.TestClass";
Object[] parameters;
Object obj =
Class.forName(classname).getConstructor(Object[].class).newInstance(new
Object[] { parameters });
What this code snippet does is:
Get the class named "org.some.class.TestClass".
(Class.forName(classname)).
Then it proceeds to get a constructor for said class, one that requires
an object array as parameter ( getConstructor(Object[].class)).
Then it proceeds to instantiate the object using said constructor,
passing the Object array "parameters" as the parameters.
There you have it - I have loaded an instance of the class
org.some.class.TestClass - without having to know that name in the code
- the String classname could have been loaded from any source (in
particular, I use that code snippet for persistence of simple objects
from a database - load the className and the constructor parameters
from the database, execute the reflection voodoo to instantiate)
.
- References:
- Reflection, how to understand
- From: John_Woo
- Reflection, how to understand
- Prev by Date: Subversion GUI, maybe in java
- Next by Date: Re: Reflection, how to understand
- Previous by thread: Re: Reflection, how to understand
- Next by thread: Subversion GUI, maybe in java
- Index(es):
Relevant Pages
|
|