态调用类方法的应用
今天看到的好文章和大家分享一下:
http://www.internetism.org/qbbs/ShowAnnounce.asp?boardID=1&RootID=375&ID=375
http://www.internetism.org/qbbs/ShowAnnounce.asp?boardID=1&RootID=375&ID=376
下面是我修改了一下的代码:
package testclass;
public class class1 { public class1(){}
public int add(int a,int b){ return a+b; }
}
package dyn_callmethod;
import java.lang.reflect.*;
import testclass.class1;
public class callclass {
public callclass() {
}
public static void main(String args[]){
try{
Class cls = Class.forName("testclass.class1");
System.out.println("Load the target class");
Class partypes[] = new Class[2];
partypes[0] = Integer.TYPE;
partypes[1] = Integer.TYPE;
Method meth = cls.getMethod("add", partypes);
System.out.println("get the method of the class");
//testclass.class1 methobj = new testclass.class1(); ///////////////////////////////////////////////////// //Class const = Class.forName("testclass.class1"); Class par[] = null; Constructor ct = cls.getConstructor(par);//因为class1的构造函数是无参的所以我就给getConstructor
输入了一个为null的Class数组做参数 /////////////////////////////////////////////////////
Object arglist[] = new Object[2];
arglist[0] = new Integer(37);
arglist[1] = new Integer(47);
//Object retobj = meth.invoke(methobj, arglist); Object retobj = meth.invoke(ct.newInstance(null), arglist);
Integer retval = (Integer)retobj;
System.out.println(retval.intValue());
}
catch(Exception e){
System.err.println(e);
}
}
}
今天看到的好文章和大家分享一下:
http://www.internetism.org/qbbs/ShowAnnounce.asp?boardID=1&RootID=375&ID=375
http://www.internetism.org/qbbs/ShowAnnounce.asp?boardID=1&RootID=375&ID=376
下面是我修改了一下的代码:
package testclass;
public class class1 { public class1(){}
public int add(int a,int b){ return a+b; }
}
package dyn_callmethod;
import java.lang.reflect.*;
import testclass.class1;
public class callclass {
public callclass() {
}
public static void main(String args[]){
try{
Class cls = Class.forName("testclass.class1");
System.out.println("Load the target class");
Class partypes[] = new Class[2];
partypes[0] = Integer.TYPE;
partypes[1] = Integer.TYPE;
Method meth = cls.getMethod("add", partypes);
System.out.println("get the method of the class");
//testclass.class1 methobj = new testclass.class1(); ///////////////////////////////////////////////////// //Class const = Class.forName("testclass.class1"); Class par[] = null; Constructor ct = cls.getConstructor(par);//因为class1的构造函数是无参的所以我就给getConstructor
输入了一个为null的Class数组做参数 /////////////////////////////////////////////////////
Object arglist[] = new Object[2];
arglist[0] = new Integer(37);
arglist[1] = new Integer(47);
//Object retobj = meth.invoke(methobj, arglist); Object retobj = meth.invoke(ct.newInstance(null), arglist);
Integer retval = (Integer)retobj;
System.out.println(retval.intValue());
}
catch(Exception e){
System.err.println(e);
}
}
}