简体   繁体   English

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

[英]How call a method in java using reflection?

I have a scenario where I instantiate a class and call a method like the one given below using java reflection mechanism. 我有一种情况,我实例化一个类并使用Java反射机制调用下面给出的方法。

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

For above case I tried using java reflection as below: 对于上述情况,我尝试使用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");

I am unable to do it particularly in the following scenario: 我无法做到这一点,特别是在以下情况下:

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

You'll need to call the getters for the instances, and then invoke methods on the returned instances using reflection as well. 您需要调用实例的getter,然后还使用反射对返回的实例调用方法。 Here's an example for workerObjectType.getID().add(workerObjectIdType) 这是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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM