简体   繁体   中英

Expose interface methods names

I'm working in a method that invoke a class method using reflection and getting my service object class from spring. Something like this:

private void InvokeMethod(string serviceName, string methodName, params object[] arguments)
    {
        object service = SpringContextManager.Instance.GetObject(serviceName);
        Type classType = service.GetType();
        MethodInfo method = classType.GetMethod(methodName);
        method.Invoke(service, arguments);
    }


//...

InvokeMethod(SpringObjectsConstants.LogDocumentService, "SetDocumentStatus", 9127, LogDocumentPendingStatusEnum.Finalized)

I need to inform the method name as a string so the method can call it, but I dont want to work with strings because if the method name changes, I can´t track the usages of it. There is any way to work with the interfaces methods that look like an enum or something? Anything that could cause compilation errors or I can update renaming the method name in visual studio?

There is a refactoring-safe way: You can use an expression and parse that. The idea is the same as in this article .
Unfortunately, it gets a bit messy when you use methods instead of properties, because you need to pass the arguments to the method.

Having said that, there is a much more elegant solution. It simply uses a delegate

However, I don't really see the need for reflection here at all. You can simply pass a delegate:

InvokeMethod<ServiceImpl>(
    SpringObjectsConstants.LogDocumentService,
    x => x.SetDocumentStatus(9127, LogDocumentPendingStatusEnum.Finalized));

This would have another advantage: If you changed the type of a parameter or added or removed a parameter from the method, you also would get a compilation error.

InvokeMethod would look like this:

private void InvokeMethod<TService>(
    string serviceName, Action<TService> method)
{
    TService service = (TService)SpringContextManager.Instance
                                                     .GetObject(serviceName);
    method(serviceName);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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