/*
My understanding on this is that JAVA REFELECTION is a container or an operator for a Class.
*/
//package reference
import java.lang.reflect.*;
//List the method(s) of a class.
...
Class c = Class.forName("ClassName");//load the class' structure
Method m[] = c.getDeclaredMethods();
for(int i = 0;i < m.length; i++){
System.out.println(m[i].getName());
}
...
//List the parameters TYPE of a method
...
Class pretype[] = m.getParameterTypes();
//Invoke a specified method
...
Class c = Class.forName("ClassName");
Class params[] = new Class[2];//2 is the operands' count.
Method m = c.getMethod("appropriateMethodName",params);
//if there is no argument in the method, need throw an exception.
ClassName cn = new ClassName();
Object args[] = new Object[2];//same with the previous CLASS.
m.invoke(cn,args);
//if there's a return value,should use a Object to receive it.like
// Object o = m.invoke(cn,args);
// then convert the type.like
// Integer i = (Integer)o;
for details:
[url]http://java.sun.com/developer/technicalArticles/ALT/Reflection/[/url]
本文介绍了Java反射机制的基本用法,包括如何获取类的方法列表、参数类型、调用指定方法等。通过示例代码展示了反射机制在Java开发中的应用。
513

被折叠的 条评论
为什么被折叠?



