3

Need to cast a Java ArrayList to C# ArrayList.

It does not work.

//code in C#
public void DoSomething(Java.Lang.Object obj){
    Java.Util.ArrayList list = (Java.Util.ArrayList) obj;
}

The Exception:

Unhandled Exception:

System.InvalidCastException: Specified cast is not valid.

When I print out obj.Class, it returns class java.util.ArrayList

How to fix it?

12
  • stackoverflow.com/questions/4581407/… Commented Dec 1, 2017 at 6:57
  • @Generic That s not what I am asking. Commented Dec 1, 2017 at 7:02
  • Looks like you are trying to cast a java.util.ArrayList to a Java.Util.ArrayList. Does not look like they are the same thing so you will not be able to cast. The Java.Util.ArrayList might be a List can you cast to the interface? Commented Dec 1, 2017 at 7:23
  • same Exception when casting to Java.Util.IList. What did you want me to cast it to? Commented Dec 1, 2017 at 7:32
  • 2
    You guys DO know that I'm trying to do C# with Java Objects here right? I mean all your comments are assuming that it's all in Java when I specifically stated that the code is in C#. Commented Dec 1, 2017 at 8:41

3 Answers 3

12
+25

I do not write C# code but if this was me and I needed to convert an object for use in a different language I would just serialize the Java object to JSON and deserialize it to my object in C#.

Sign up to request clarification or add additional context in comments.

1 Comment

This is also how I would approach it. Serialize the object into JSON or some string representation of the data that is easy to parse. Depending on the size and way the method is called and data passed, I may also compress with something like MessagePack.
2

I think you need this amazing library: https://www.ikvm.net/ by Jeroen Frijters & contributors.

IKVM.NET is an implementation of Java for Mono and the Microsoft .NET Framework. It includes the following components:

A Java Virtual Machine implemented in .NET
A .NET implementation of the Java class libraries
Tools that enable Java and .NET interoperability

This is such a massive subject, you'll have to do a few tutorials, eg Convert a Java Application to .NET. Good luck!

Comments

1

It is ready in Xamarin, just add:

using Android.Gms.Extensions;

then:

var list = listAsObject.JavaCast<ArrayList>();

1 Comment

The JavaCast<T>() Extension is part of Android.Runtime or Java.Interop namespace. But yes, JavaCast is the way to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.