DEV Community

Mario Mastrodicasa
Mario Mastrodicasa

Posted on Originally published at Medium on

JCOReflector: bringing .NET APIs to the JVM — and now with generics


Photo by Michiel Leunens on Unsplash

If you’ve read about JNet, you already know the shape of the problem: running two runtimes side by side, in one process, without marshalling everything through JSON or a TCP socket. JNet solves it in one direction — a real JVM inside a .NET process, with the Java API surface exposed as C#. JCOReflector solves it in the other direction: a real CLR inside a JVM process, with the .NET API surface exposed as Java (and, by extension, Scala, Kotlin, and Clojure, since they all compile to the same bytecode).

Both tools sit on top of JCOBridge, the library that actually owns the inter-runtime boundary. JCOReflector’s job is narrower and more mechanical: point it at a .NET assembly, and it generates a complete, compilable Java class for every public type it finds — constructors, methods, properties, events, exceptions, the works — so that calling into .NET from Java looks and feels like calling into any other Java library.

This article covers what JCOReflector generates today, and — the reason this is worth writing now — the support for .NET generics that just landed, including where it genuinely can't follow .NET's lead and why.

What a generated class looks like

Point the CLI at an assembly:

MASES.JCOReflectorCLI -JobType Reflect -JobFile reflect.job
Enter fullscreen mode Exit fullscreen mode

using the configuration file:

<?xml version="1.0" encoding="utf-8"?>
<ReflectorEventArgs xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <LogLevel>Error</LogLevel>
  <AssemblyNames>
    <string>PresentationFramework, Version=8.0.0.0</string>
  </AssemblyNames>
  <SourceFolder>src/jvm</SourceFolder>
  <SplitFolderByAssembly>true</SplitFolderByAssembly>
  <ForceRebuild>true</ForceRebuild>
  <UseParallelBuild>true</UseParallelBuild>
  <CreateExceptionThrownClause>true</CreateExceptionThrownClause>
  <ExceptionThrownClauseDepth>10</ExceptionThrownClauseDepth>
  <EnableAbstract>true</EnableAbstract>
  <EnableArray>true</EnableArray>
  <EnableDuplicateMethodNativeArrayWithJCRefOut>true</EnableDuplicateMethodNativeArrayWithJCRefOut>
  <EnableInheritance>true</EnableInheritance>
  <EnableInterfaceInheritance>true</EnableInterfaceInheritance>
  <EnableRefOutParameters>true</EnableRefOutParameters>
  <EnableGenerics>true</EnableGenerics>
  <DryRun>false</DryRun>
</ReflectorEventArgs>
Enter fullscreen mode Exit fullscreen mode

What comes out isn’t a thin proxy — it’s a real Java class with a real relationship to the .NET type behind it. Three conventions carry through every single generated file:

  • Properties become explicit getX()/setX() pairs. .NET property syntax has no Java equivalent, so there's no attempt to fake it — list.Count becomes list.getCount().
  • Events become explicit addX/** removeX methods**, not +=/-=. A System.Timers.Timer in Java looks like:
Timer timer = new Timer();
TimerElapsed elapsed = new TimerElapsed();
timer.addElapsed(elapsed);
timer.setInterval(1000);
timer.setEnabled(true);
// ...
timer.removeElapsed(elapsed);
Enter fullscreen mode Exit fullscreen mode
  • [Flags] enums get add(...)/remove(...) methods standing in for |=/&= ~, since Java doesn't allow overloading bitwise operators on an enum type.

Underneath, every generated class implements a single marker interface, IJCOBridgeReflected, and carries the metadata needed to round-trip itself across the bridge: a className field holding the fully-qualified CLR type name, and a getJCOInstance()/setJCOInstance() pair that exposes the underlying native handle. That marker interface turns out to matter a lot once generics enter the picture.

The generics problem

Until recently, JCOReflector simply discarded every generic .NET type and member during reflection. A generic class, interface, delegate, or method was invisible to the generator — which meant List, Dictionary, Task, and most of LINQ never showed up in the generated output at all. For a tool whose whole purpose is exposing the .NET API surface, that's a conspicuous gap: most of modern .NET is generic.

The reason it was skipped isn’t laziness — it’s a real mismatch between how the two platforms implement generics. .NET generics are reified: List and List are distinct types at runtime, each with its own compiled code and its own static state. Java generics are implemented via type erasure: List and List share one compiled class, and every trace of the type argument is gone by the time the bytecode runs. Closing that gap means working around erasure everywhere it would otherwise be a compile error — and, in a few well-defined cases, admitting that a particular .NET generic API simply has no honest Java representation.

How it works: the “super type token” trick

A reflected generic .NET type becomes a parameterized Java class, with every type parameter bounded by IJCOBridgeReflected:

public class List_1<T extends IJCOBridgeReflected> extends NetObject { ... }
Enter fullscreen mode Exit fullscreen mode

(the _1 suffix is an arity marker — Dictionary_2, Lazy_1 vs Lazy_2 — needed because .NET allows same-named types with different arity, which Java's package namespace doesn't distinguish on its own.)

Constructing one of these requires a trailing {}:

List_1<NetObject> list = new List_1<NetObject>() {};
list.Add(new NetObject());
Enter fullscreen mode Exit fullscreen mode

That trailing {} isn't decoration — it's the whole mechanism. It's the same "super type token" idiom used by Gson's TypeToken and Guava: erasure throws away a class's own generic type argument, but the JVM does keep that information on the supertype of an anonymous subclass. new List_1(){}.getClass().getGenericSuperclass() hands back a ParameterizedType carrying Foo.class, intact. Construct without the {} and you get a clear, immediate IllegalArgumentException rather than a confusing failure three calls later.

That recovered Class<?> is cached on the instance and reused by a small reflective helper, instantiateGenericArgument, anywhere the generated code needs to build a new instance of the type parameter — because new T(...) is flatly illegal Java (erasure removes T at runtime; the compiler has nothing to new). An array of T has the same problem and the same fix, via java.lang.reflect.Array.newInstance instead of new T[].

Generic delegates needed a variant of the same trick. Comparison, Func, and friends extend JCDelegate rather than NetObject, so they can't reuse NetObject's machinery directly — a small shared helper, NetGenericHelper, plays the same role, resolving the closed CLR delegate type lazily the first time it's needed instead of requiring the caller to build a type name by hand. From the call site, it looks exactly like everything else:

List_1<system.Object> list = new List_1<system.Object>() {};
list.Add(new system.Object());
list.Add(new system.Object());
Comparison_1<system.Object> comparison = new Comparison_1<system.Object>() {
    @Override
    public int Invoke(system.Object x, system.Object y) {
        return 0; // real comparison logic goes here
    }
};
list.Sort(comparison);
Enter fullscreen mode Exit fullscreen mode

Same new X() {} idiom whether X is a collection or a delegate; the type argument recovery and the CLR-side type resolution both happen underneath, out of the caller's way.

Where it has to say no

Not everything maps. Four categories are excluded on purpose, and it’s worth being explicit about why, rather than leaving them as silent gaps:

  • ref struct types  — Span, ReadOnlySpan. These wrap a native pointer or stack reference that can't be boxed and can't cross the bridge as an object. There's no Java representation for this, period; the type and anything that uses it as a parameter or return type is skipped entirely.
  • “Generic math” interfaces  — INumber and the whole C# 11 family built on static abstract interface members. Java interfaces can't declare a static abstract member at all — there's no partial solution here, the feature just doesn't exist on the JVM side.
  • A type parameter that belongs to a method, not a class. List's own T can be recovered because an instance exists to hang the anonymous-subclass trick on. Array.Empty() has no instance — there's no moment where a Class is ever available — so it's skipped rather than emitting code that references an unresolvable type.
  • A class-level type parameter referenced from a static member. .NET gives every closed generic instantiation its own independent static state; Java has exactly one shared class per raw type regardless of how many parameterizations exist. A static method genuinely cannot see the class's own T in Java, so these are skipped too.

A fifth case doesn’t skip anything — it renames. Some .NET members only collide because erasure throws away the information that made them distinct: IEqualityComparer.Equals(T, T) would otherwise erase to the exact same signature as the base Equals(IJCOBridgeReflected, IJCOBridgeReflected) every generated class already has, so it's emitted as EqualsGeneric(...) instead of being lost. KeyedCollection.Remove(TKey) becomes RemoveByKey(...) for the same reason, against the inherited Collection.Remove(TItem).

And one case is a hard language rule with no workaround at all: a generic class can never extend java.lang.Throwable (JLS §8.1.2). A .NET generic exception like FaultException is therefore always generated as a plain, non-generic class, with TDetail exposed everywhere as its bound, IJCOBridgeReflected, rather than as a real type variable. It's the one spot where the generic parameter is erased to its bound in the public API, not just internally — by necessity, not by choice.

Current status

Generics are controlled by a single engine switch (EnableGenerics), off by default in the reflector tool and enabled in the CI that produces the published JARs. The mechanisms above are implemented and test-covered — collections, generic delegates as synchronous callbacks, the rename strategy for erasure collisions, the exception fallback — across every target JVM language the project supports, not just Java.

Two things are explicitly still open, and worth naming rather than glossing over: a handful of .NET interfaces remain excluded pending further work — IAlternateEqualityComparer (.NET 9+, a two-different-type-parameter variant of the Equals collision the rename logic doesn't yet detect) and INameScopeDictionary (whose generated wrapper class currently only collects members declared directly on the interface, not the full inherited interface closure).

Where to go from here

Top comments (0)