import java.lang.reflect.*;
import java.util.*;
public class DynTest {
public double d; // a field
public int add(int a, int b)
{
System.out.println("add() invoked");
return a + b;
}
public String tName(String s, Hashtable ht)
{
System.out.println("tName() invoked");
return s;
}
public static void main(String args[])
{
//代刚1. Method.invoke()
{
try {
Class c = Class.forName("DynTest");
Class pTypes[] = new Class[2];
pTypes[0] = Integer.TYPE;
pTypes[1] = Integer.TYPE;
Method m = c.getMethod("add", pTypes);
DynTest obj = new DynTest();
Object arg[] = new Object[2];
arg[0] = new Integer(37);
arg[1] = new Integer(47);
Object r = m.invoke(obj, arg);
Integer rVal = (Integer)r;
System.out.println("return: "+rVal.intValue()); //84
}
catch (Throwable e) {
System.err.println(e);
}
}
//代刚2. Method.invoke()
{
try {
Class c = Class.forName("DynTest");
Class pTypes[] = new Class[2];
pTypes[0] = Class.forName("java.lang.String");
pTypes[1] = Class.forName("java.util.Hashtable");
Method m = c.getMethod("tName", pTypes);
Object arg[] = new Object[2];
arg[0] = new String("return: "+"Hello,World!");
arg[1] = null;
//ERROR: non-static variable this cannot be referenced from a static context
DynTest obj = new DynTest();
Object r = m.invoke(obj, arg);
String rVal = (String)r;
System.out.println(rVal); //Hello,World!
}
catch (Throwable e) {
System.err.println(e);
}
}
//代刚3. Field.setDouble()
{
try {
Class c = Class.forName("DynTest");
Field f = c.getField("d");
DynTest obj = new DynTest();
System.out.println("before setting, d= " + obj.d); //0.0
f.setDouble(obj, 12.34);
System.out.println("after setting, d= " + obj.d); //12.34
}
catch (Throwable e) {
System.err.println(e);
}
}
} //main
}
posted on 2005-08-23 21:25
R.Zeus 阅读(298)
评论(0) 编辑 收藏 所属分类:
Reflection