Java動態調用類中方法代碼_java

來源:互聯網
上載者:User

在Java中,調用類的方法有兩種方式:對於靜態方法可以直接使用類名調用,對於非靜態方法必須使用類的對象調用。反射機制提供了比較另類的調用方式,可以根據需要指定要調用的方法,而不必在編程時確定。調用的方法不僅限於public的,還可以是private的。編寫程式,使用反射機制調用Math類的靜態方法sin()和非靜態方法equals()。

思路如下:使用Math.class.getDeclaredMethod("sin", Double.TYPE);訪問指定的方法,其中”sin”表示要訪問的方法的名稱為sin,Double.TYPE表示入口參數的類型為double。

代碼如下:

複製代碼 代碼如下:

import java.lang.reflect.Method;

public class DongTai {
    public static void main(String[] args) {
        try {
            System.out.println("調用Math類的靜態方法sin()");
            Method sin = Math.class.getDeclaredMethod("sin", Double.TYPE);
            Double sin1 = (Double) sin.invoke(null, new Integer(1));
            System.out.println("1的正弦值是:" + sin1);
            System.out.println("調用String類的非靜態方法equals()");
            Method equals = String.class.getDeclaredMethod("equals", Object.class);
            Boolean mrsoft = (Boolean) equals.invoke(new String("明日科技"), "明日科技");
            System.out.println("字串是否是明日科技:" + mrsoft);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

效果如圖:

聯繫我們

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