amccormack
amccormack

Reputation: 13927

Method unavailable when using reflection - TargetInvocationError

I have been able to successfully execute other methods using reflection but I am now getting a TargetInvocationException. Although the TargetInvoationException points me to the methodInfo.Invoke method, stepping through the code shows the exception occuring in the Load method when SampleXMLToDataTable is called. The SampleXMLToDataTable is a public static method in the same class as Load. The error is thrown as the code is attempting to enter the SampleXMLToDataTable.

Is there a problem calling methods from within other methods that are being called using reflection?

The code that calls via reflection:

 private Object CreateXMLDataLoaderInstance(string xml)
 {
  object o = null;

  Assembly demandAssembly = LoadSampleDemandAssembly();
  Type assemblyType = demandAssembly.GetType("SampleDemand.XMLDataLoader");
  MethodInfo methodInfo = assemblyType.GetMethod("Load");
  o = Activator.CreateInstance(assemblyType, new Object[1] { true });

  Object[] oParamArray2 = new Object[1];

  methodInfo.Invoke(o, new Object[1] { xml });//TargetInvocationException

  return o;
 }

And the method it is trying to invoke:

 public void Load(string xml)
{
  XmlDocument xDoc = new XmlDocument();
  xDoc.LoadXml(xml);

  XmlNode settingsNode = null;
  foreach (XmlNode xNode in xDoc.FirstChild.ChildNodes)
  {
    string name = xNode.Name;
    string wsx = xNode.ChildNodes[0].OuterXml;

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(wsx);
    DataTable dt = SampleXMLToDataTable(doc);//Where the code breaks
    XMLSample xmlWS = new XMLSample(dt, wsx, name);

    this.sample.Add(name, xmlWS);
  }
  if (settingsNode != null)
  {
    settings = GetSettings(settingsNode);
  }
}

Upvotes: 0

Views: 234

Answers (2)

Brian Rudolph
Brian Rudolph

Reputation: 6318

Your error just means that an exception is being thrown somewhere in the invoked method. This is exactly what you have pointed out. Your SampleXMLToDataTable method is throwing an exception. This has nothing to do with calling it via reflection. I suspect that if you call it directly, you will get an exception in the exact same spot.

This is not a limitation of reflection, you just get a different exception because you are invoking it through reflection, though the inner exception of the TargetInvocationException should give you more information.

Upvotes: 1

jason
jason

Reputation: 241769

Is there a problem calling methods from within other methods that are being called using reflection?

No, TargetInvocationException means that the method was successfully invoked by reflection, but that the target method threw an exception. Look at the InnerException property of the TargetInvocationException for details on the exception that was thrown by the target method.

Upvotes: 1

Related Questions