如何使用反射调用Java中的方法?

时间:2019-06-28 05:15:06

标签: java reflection

我有一种情况,我实例化一个类并使用java反射机制调用下面给出的方法。

    WorkerObjectType workerObjectType = new WorkerObjectType();
    WorkerObjectIDType workerObjectIdType = new WorkerObjectIDType();
    workerObjectIdType.setType("Employee_ID");
    workerObjectIdType.setValue("102");
    workerObjectType.getID().add(workerObjectIdType);
    workerReqReferenceType.getWorkerReference().add(workerObjectType);

对于上述情况,我尝试使用Java反射,如下所示:

Class<?> workerObjectTypeRef = Class.forName("platinum.humanresource.WorkerObjectType");
Object workerObjectType = workerObjectTypeRef.newInstance();
Class<?> workerObjectIDTypeRef = Class.forName("platinum.humanresource.WorkerObjectIDType");
Object workerObjectIdType = workerObjectIDTypeRef.newInstance();
Method setType = workerObjectIDTypeRef.getDeclaredMethod("setType", String.class);
setType.invoke(workerObjectIdType, "Employee_ID");
Method setValue = workerObjectIDTypeRef.getDeclaredMethod("setValue", String.class);
setValue.invoke(workerObjectIdType, "102");

我无法做到这一点,特别是在以下情况下:

workerObjectType.getID().add(workerObjectIdType);
workerReqReferenceType.getWorkerReference().add(workerObjectType);

1 个答案:

答案 0 :(得分:0)

您将需要调用实例的getter,然后还使用反射对返回的实例调用方法。这是workerObjectType.getID().add(workerObjectIdType)

的示例
Method getID = workerObjectTypeRef.getDeclaredMethod("getID");
Object id = getID.invoke(workerObjectType);
Class idRef = id.getClass();
Method add = idRef.getDeclaredMethod("add", workerObjectIDTypeRef);
add.invoke(id, workerObjectIDType);