import java.lang.reflect.*;
public class ConstructorDemo{
public ConstructorDemo(){ }
public ConstructorDemo(int a, int b){
System.out.println("a="+a+"b="+b);
}
public static void main(String args[]){
try {
Class cls = Class.forName("ConstructorDemo");
Class partypes[] = new Class[2]; partypes[0] = Integer.TYPE;
partypes[1] = Integer.TYPE;
Constructor ct= cls.getConstructor(partypes);
Object arglist[] = new Object[2];
arglist[0] = new Integer(37);
arglist[1] = new Integer(47);
Object retobj = ct.newInstance(arglist);
} catch (Throwable e) {
System.err.println(e); }
}
}
2、属性
步骤为:通过反射机制得到某个类的某个属性,然后改变对应于这个类的某个实例的该属性值
import java.lang.reflect.*;
public class FieldDemo1{
public double d;
public static void main(String args[]){
try {
Class cls = Class.forName("FieldDemo1");
Field fld = cls.getField("d");
FieldDemo1 fobj = new FieldDemo1();
System.out.println("d = " + fobj.d);
fld.setDouble(fobj, 12.34);
System.out.println("d = " + fobj.d);
} catch (Throwable e){
System.err.println(e); }
}
}
3、方法
步骤为:通过反射机制得到某个类的某个方法,然后调用对应于这个类的某个实例的该方法
//通过使用方法的名字调用方法
import java.lang.reflect.*;
public class MethodDemo1{
public int add(int a, int b){
return a + b;
}
public static void main(String args[]){
try {
Class cls = Class.forName("MethodDemo1");
Class partypes[] = new Class[2];
partypes[0] = Integer.TYPE;
partypes[1] = Integer.TYPE;
Method meth = cls.getMethod("add", partypes);
MethodDemo1 methobj = new MethodDemo1();
Object arglist[] = new Object[2];
arglist[0] = new Integer(37);
arglist[1] = new Integer(47);
Object retobj= meth.invoke(methobj, arglist);
Integer retval = (Integer)retobj;
System.out.println(retval.intValue());
} catch (Throwable e) {
System.err.println(e);
}
}
}