簡體   English   中英

如何使用反射調用 java 中的方法

[英]How to invoke a method in java using reflection

如何使用反射調用帶有參數的方法?

我想指定這些參數的值。

這是一個使用包含原語的反射調用方法的簡單示例。

import java.lang.reflect.*;

public class ReflectionExample {
    public int test(int i) {
        return i + 1;
    }
    public static void main(String args[]) throws Exception {
        Method testMethod = ReflectionExample.class.getMethod("test", int.class);
        int result = (Integer) testMethod.invoke(new ReflectionExample(), 100);
        System.out.println(result); // 101
    }
}

為了健壯,您應該捕獲並處理所有已檢查的與反射相關的異常NoSuchMethodExceptionIllegalAccessExceptionInvocationTargetException

使用反射調用類方法非常簡單。 您需要在其中創建一個類並生成方法。 如下。

package reflectionpackage;

public class My {
    public My() {
    }

    public void myReflectionMethod() {
        System.out.println("My Reflection Method called");
    }
}

並使用反射在另一個類中調用此方法。

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

public class ReflectionClass {

    public static void main(String[] args) 
    throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Class c=Class.forName("reflectionpackage.My");
        Method m=c.getDeclaredMethod("myReflectionMethod");
        Object t = c.newInstance();
        Object o= m.invoke(t);       
    } 
}

在此處查找更多詳情

您可以在任何Object中使用getClass來發現它的類。 然后,您可以使用getMethods來發現所有可用的方法。 一旦有了正確的方法,就可以使用任意數量的參數調用invoke

這是我所知道的最簡單的方法,它需要被try&catch包圍:

方法m = .class.getDeclaredMethod(“”,arg_1.class,arg_2.class,... arg_n.class); result =()m.invoke(null,(Object)arg_1,(Object)arg_2 ...(Object)arg_n);

這是用於調用靜態方法,如果要調用非靜態方法,則需要將m.invoke()的第一個參數從null替換為調用基礎方法的對象。

不要忘記向java.lang.reflect添加導入。*;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM