Skip to content

Instantly share code, notes, and snippets.

@Cheesebaron
Last active March 15, 2023 19:30
Show Gist options
  • Save Cheesebaron/9876783 to your computer and use it in GitHub Desktop.
Save Cheesebaron/9876783 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;
}
}
@Cheesebaron
Copy link
Author

@maikoly1 why are you serializing it?

@maikoly1
Copy link

maikoly1 commented Apr 14, 2020 via email

@Cheesebaron
Copy link
Author

You should probably not serialize JavaHolder

@xiaochao00
Copy link

Hi, I have two questions:

  1. How do I get Java.Lang.Object? Does it come from IKVM?
  2. Does it in IKVM named java.lang.Object?

@Cheesebaron
Copy link
Author

Cheesebaron commented Sep 21, 2022

@xiaochao00 no this is for Xamarin.Android.

I don't know if there is an equivalent for IKVM.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment