簡體   English   中英

使用反射來調用字段上的方法

[英]Using reflection to invoke method on field

我的代碼如下所示:

class MyObject {

    MyField f = new MyField();

}

class MyField {
    public void greatMethod();
}

有沒有辦法使用MyObject類對象的反射來調用greatMethod()

我嘗試了以下方法:

Field f = myObject.getClass().getDeclaredField("f");
Method myMethod = f.getDeclaringClass().getDeclaredMethod("greatMethod", new Class[]{});
myMethod.invoke(f);

但是它試圖直接在我的myObject上調用greatMethod()而不是在其中的字段f上調用。 有沒有辦法實現這一點,而無需修改MyObject類(因此它將實現一個在f上調用適當方法的方法)。

你是親密的,你只需要獲取聲明的方法並在對象實例中包含的字段的實例上調用它,而不是在字段中調用它,如下所示

    // obtain an object instance
    MyObject myObjectInstance =  new MyObject();

    // get the field definition
    Field fieldDefinition = myObjectInstance.getClass().getDeclaredField("f");

    // make it accessible
    fieldDefinition.setAccessible(true);

    // obtain the field value from the object instance
    Object fieldValue = fieldDefinition.get(myObjectInstance);

    // get declared method
    Method myMethod =fieldValue.getClass().getDeclaredMethod("greatMethod", new Class[]{});

    // invoke method on the instance of the field from yor object instance
    myMethod.invoke(fieldValue);

暫無
暫無

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

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