通过Java反射调用方法

阅读更多
import java.lang.reflect.Method; 
import java.lang.reflect.InvocationTargetException; 

/** 
* Created by IntelliJ IDEA. 
* File: TestRef.java 
* User: leizhimin 
* Date: 2008-1-28 14:48:44 
*/ 
public class TestRef { 

    /**
     *通过类地址来调用
     */
    public void test() {
		try {
			Class clazz = Class.forName("com.xlwz.wizard.impl.ChooseJdkprocess");
			Method getRootPath = clazz.getDeclaredMethod("getRootPath");
			System.out.println(getRootPath.invoke(clazz.newInstance()));
		} catch (Exception e) {
		}
	}

    public static void main(String args[]) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { 
        Foo foo = new Foo("这个一个Foo对象!"); 
        Class clazz = foo.getClass(); 
        Method m1 = clazz.getDeclaredMethod("outInfo"); 
        Method m2 = clazz.getDeclaredMethod("setMsg", String.class); 
        Method m3 = clazz.getDeclaredMethod("getMsg"); 
        m1.invoke(foo); 
        m2.invoke(foo, "重新设置msg信息!"); 
        String msg = (String) m3.invoke(foo); 
        System.out.println(msg); 
    } 
} 

class Foo { 
    private String msg; 

    public Foo(String msg) { 
        this.msg = msg; 
    } 

    public void setMsg(String msg) { 
        this.msg = msg; 
    } 

    public String getMsg() { 
        return msg; 
    } 

    public void outInfo() { 
        System.out.println("这是测试Java反射的测试类"); 
    } 
}

调用静态方法
public static void Test(){
		System.out.println("123");
	}
	
	public static void main(String[] args) throws Exception {
		Class c; 		
		c = Class.forName("link.Test3"); 		
		Method m = c.getMethod("Test"); 		
		m.invoke(c); 
	}

控制台输出结果:
这是测试Java反射的测试类 
重新设置msg信息! 

Process finished with exit code 0 

http://lavasoft.blog.51cto.com/62575/61002

你可能感兴趣的:(java,反射机制)