Skip to content

Instantly share code, notes, and snippets.

@jeremejazz
Forked from Cheesebaron/JavaHolder.cs
Created October 8, 2016 13:05
Show Gist options
  • Save jeremejazz/1b19b80019e5794dac6049ce173f2cbd to your computer and use it in GitHub Desktop.
Save jeremejazz/1b19b80019e5794dac6049ce173f2cbd to your computer and use it in GitHub Desktop.
C# to Java object wrapper
using System;
public class JavaHolder : Java.Lang.Object
{
public readonly object Instance;
public JavaHolder(object instance)
{
Instance = instance;
}
}
using System;
public static class ObjectExtensions
{
public static TObject ToNetObject<TObject>(this Java.Lang.Object value)
{
if (value == null)
return default(TObject);
if (!(value is JavaHolder))
throw new InvalidOperationException("Unable to convert to .NET object. Only Java.Lang.Object created with .ToJavaObject() can be converted.");
TObject returnVal;
try { returnVal = (TObject) ((JavaHolder) value).Instance; }
finally { value.Dispose(); }
return returnVal;
}
public static Java.Lang.Object ToJavaObject<TObject>(this TObject value)
{
if (Equals(value, default(TObject)) && !typeof(TObject).IsValueType)
return null;
var holder = new JavaHolder(value);
return holder;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment