[Java] – 通過反射調用對象的方法

來源:互聯網
上載者:User

來源:http://user.qzone.qq.com/31584 (QQ空間)

        http://b.qzone.qq.com/cgi-bin/blognew/blog_output_data?uin=31584&blogid=1270205768&styledm=qzonestyle.gtimg.cn&imgdm=qzs.qq.com&bdm=b.qzone.qq.com&mode=2&numperpage=15&blogseed=0.7275722332481711&property=GoRE&timestamp=1273108498 (實際地址)

 

 TestRef.java

import java.lang.reflect.Method; 
import java.lang.reflect.InvocationTargetException;

/**
* Created by IntelliJ IDEA.
* File: TestRef.java
* User: String
* Date: 2010-3-29 14:48:44
*/
public class TestRef {

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反射的測試類別");
}
}

 

 

控制台輸出結果:

這是測試Java反射的測試類別 
重新設定msg資訊!

Process finished with exit code 0

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.