天天看点

使用反射调用一个类的方法

下面用例子程序来说明:

import java.lang.reflect.Method;

public class WhtTest {
    public static void main( String[] args ) throws Exception {
        Count c = new Count( 2, 3 );
        Method m = Count.class.getMethod( "plus" );
        System.out.println( m.invoke( c ) ); // 5
    }

}

class Count {
    int a;

    int b;

    public Count( int a, int b ) {
        this.a = a;
        this.b = b;
    }

    public int plus() {
        return this.a + this.b;
    }

}