Search code examples
c#ikvm

Passing enumeration value to Java constructor from C#


I've a requirement to run JAR files from C# using IKVM. The JAR contains a class whose constructor takes an enumeration as one of its parameter. The problem I'm facing is that when I try to create an instance of this class in C# using IKVM an IllegalArgumentException is thrown.

Java enum:

public class EventType{
  public static final int General;
  public static final int Other;
  public static int wrap(int v);
}

Java Class:

public class A{
   private EventType eType;
   public A(EventType e){
     eType = e;
   }
}

C# Usage:

/* loader is the URLClassLoader for the JAR files */
java.lang.Class eArg = java.lang.Class.forName("A", true, loader);

/* Instantiate with the underlying value of EventType.General */
object obj = eArg.getConstructor(EventType).newInstance(0); 

eArg is correctly loaded by the forName(..) method. However, the instantiation of the eArg class throws the IllegalArgumentException. There's no message in the exception except for the exception.TargetSite.CustomAttributes specifying that the method is not implemented. I've also tried to pass the constructor argument as a java.lang.Field object, but even that gave the same exception.

Does anyone have any suggestions on what I might be doing wrong?


Solution

  • Instead of passing 0 (the underlying value), you need to pass the (boxed) enum value. So this should work:

    /* loader is the URLClassLoader for the JAR files */
    java.lang.Class eArg = java.lang.Class.forName("A", true, loader);
    
    /* Instantiate with the underlying value of EventType.General */
    object obj = eArg.getConstructor(EventType).newInstance(EventType.General);