使用类的反射机制执行类中的方法

来源:互联网 发布:数据瀑布图画法 编辑:程序博客网 时间:2024/04/30 05:09
package lei;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;/** * 使用类的反射机制,执行类里边的方法 * @author Administrator * */public class Methodfs {    @SuppressWarnings({ "unchecked", "rawtypes" })    public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {        A a=new A();        Class c=a.getClass();//      Method m=c.getMethod("print", new Class[]{int.class,int.class});        Method m=c.getMethod("print", int.class,int.class);        Object obj=m.invoke(a, 3,4);        //当要执行的方法没有返回值时,返回null,如果有返回值,则获得具体的返回值,需要强制类型转换        System.out.println("返回值乘积:"+obj);    }}class A{    public int print(int i,int j){        System.out.println("和为:"+(i+j));        return j*i;    }}
0 0
原创粉丝点击