[mono-android] Java reflection with Mono for Android...

Jonathan Pryor jonp at xamarin.com
Tue Jan 3 11:26:01 EST 2012


On Jan 3, 2012, at 9:33 AM, Droider wrote:
> Is there any way that this can be achieved using Mono for Android? and if so how?

You can use Android.Runtime.JNIEnv to perform runtime type querying operations.

	http://docs.xamarin.com/android/advanced_topics/api_design#Java_Native_Interface_Support

For example, the code from http://code.google.com/p/android/issues/detail?id=5427#c19:

	BluetoothServerSocket interrogateSock; // your server socket
	Field mSocketField = BluetoothServerSocket.class.getDeclaredField("mSocket");
	mSocketField.setAccessible(true);
	BluetoothSocket socket = (BluetoothSocket) mSocketField.get(interrogateSock);
	mSocketField.setAccessible(false);

	Field mPortField = BluetoothSocket.class.getDeclaredField("mPort");
	mPortField.setAccessible(true);
	int port = (Integer) mPortField.get(socket); // this is what we need
	mPortField.setAccessible(false);

could be translated as (untested):

	BluetoothServerSocket interrogateSock; // your server socket

	IntPtr BluetoothServerSocket = interrogateSock.Class.Handle;

	IntPtr mSocketField = JNIEnv.GetFieldID (BluetoothServerSocket, "mSocket", "Landroid/bluetooth/BluetoothSocket;");
	IntPtr mSocketHandle = JNIEnv.GetObjectField (interrogateSock.Handle, mSocketField);
	BluetoothSocket socket = Java.Lang.Object.GetObject<BluetoothSocket>(mSocketHandle, JniHandleOwnership.TransferLocalRef);

	IntPtr BluetoothSocket = socket.Class.Handle;
	IntPtr mPortField = JNIEnv.GetFieldID (BluetoothSocket, "mPort", "I");
	int port = JNIEnv.GetIntField (socket.Handle, mPortField);

Thanks,
 - Jon



More information about the Monodroid mailing list