JAVA 中 getMethod()和invoke()方法應用

來源:互聯網
上載者:User

轉自:http://www.blogjava.net/vesung/archive/2008/01/24/177447.html 

一個簡單的需求的實現:
在程式中調用某類的某方法,並將返回結果println() 出來。
實現方法:

MethodTest.java

import java.util.ArrayList;
import java.util.List;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;

/**
 * 功能描述:
 *
 * @author <a href='mailto:vesung@gmail.com'>wangjing</a>
 * Copyright: Copyright (c) 2006-2008 by vesung.cn.
 * Date: 2008-1-23 14:13:26
 */
public class MethodTest{
    TestVO vo = new TestVO();

    /**
     * 初始化vo
     */
    protected void setUp(){
        vo.setInvoiceSortCode("InvoiceSortCode");
        vo.setInvoiceSortName("InvoiceSortName");
        vo.setOperaddress("Operaddress");
        vo.setStockStatus("StockStatus");
        vo.setStockStatusCode("StockStatusCode");
        List list = new ArrayList();
        list.add("StockStatusList");
        vo.setStockStatusList(list);
        vo.setTaxpayerName("TaxpayerName");
        vo.setTaxRegCode("TaxRegCode");
    }

    public static void main(String[] args) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        MethodTest m = new MethodTest();
        m.setUp();
        //待執行的方法名稱注意沒有()
        String methodName = "getInvoiceSortCode";

        //先擷取相應的method對象
        //getMethod第一個參數是方法名,第二個參數是該方法的參數類型,
        //因為存在同方法名不同參數這種情況,所以只有同時指定方法名和參數類型才能唯一確定一個方法
        Method method = m.vo.getClass().getMethod(methodName,new Class[0]);
        //接下來就該執行該方法了,解釋一下參數
        //第一個參數是具體調用該方法的對象
        //第二個參數是執行該方法的具體參數
        System.out.println(methodName+"():"+method.invoke(m.vo,new Object[0]));
    }
}

TestVO.java

import java.util.List;

/**
 * 功能描述:
 *
 * @author <a href='mailto:vesung@gmail.com'>wangjing</a>
 * Copyright: Copyright (c) 2006-2008 by vesung.cn.
 * Date: 2008-1-23 14:17:14
 */
public class TestVO {
    private String taxRegCode;
    private String stockStatusCode;
    private String stockStatus;
    private List stockStatusList;
    private String taxpayerName;
    private String operaddress;
    private String invoiceSortCode;
    private String invoiceSortName;
    public String pub;

        public String getInvoiceSortCode(){
                return InvoiceSortCode;
        }
//省略getter(),setter()
//  

} 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.