Java反射中Method類invoke方法的用法

來源:互聯網
上載者:User

import java.lang.reflect.Method;

public class InvokeTester {

 public int add(int param1, int param2) {  return param1 + param2; }

 public String echo(String mesg) {  return "echo" + mesg; }

 public static void main(String[] args) throws Exception {  Class classType = InvokeTester.class;  Object invokertester = classType.newInstance();    Method addMethod = classType.getMethod("add", new Class[] { int.class,    int.class });  //Method類的invoke(Object obj,Object args[])方法接收的參數必須為對象,  //如果參數為基本類型資料,必須轉換為相應的封裝類型的對象。invoke()方法的傳回值總是對象,  //如果實際被調用的方法的傳回型別是基本類型資料,那麼invoke()方法會把它轉換為相應的封裝類型的對象,  //再將其返回  Object result = addMethod.invoke(invokertester, new Object[] {    new Integer(100), new Integer(200) });  //在jdk5.0中有了裝箱 拆箱機制 new Integer(100)可以用100來代替,系統會自動在int 和integer之間轉換  System.out.println(result);

  Method echoMethod = classType.getMethod("echo",    new Class[] { String.class });  result = echoMethod.invoke(invokertester, new Object[] { "hello" });  System.out.println(result); }}

聯繫我們

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