I want to instantiate an NdefMessage using an NdefRecord with Reflection. Below a simple codeSnippet that really SHOULD work, but doesn’t:
// getting Ndef Message Class OK
Class<?> ndefMessageClass = Class.forName("android.nfc.NdefMessage");
//getting NdefRecord class OK
Class<?> ndefRecordClass = Class.forName("android.nfc.NdefRecord");
//getting ArrayOf NdefRecord
Object[] ndefRecords = (Object[])Array.newInstance(ndefRecordClass, 1)
//filling the new Array
//I'm shure I get an Correct NdefRecord, but dont wanna mess the Code here
ndefRecords[0] = getNdefRecord()
//getting the constructor OK
Constructor<?> const = ndefMessageClass.getConstructor(ndefRecords.class)
//initialization fails here
Object myNdefMessage = const.newInstance(ndefRecords)
//same with this
Object ndefMessage = const.newInstance(Arrays.asList(args).toArray());
I can absolutly NOT think of how this can fail, getting following ErrorMessage:
04-16 15:38:42.113: W/System.err(13360): java.lang.IllegalArgumentException: argument 1 should have type android.nfc.NdefRecord[], got android.nfc.NdefRecord
So I get a Constructor recognized correctly. If I try to get it like this:
Constructor<?> const = ndefMessageClass.getConstructor(ndefRecords[0].getClass())
I get
04-16 15:44:59.621: W/System.err(14033): java.lang.NoSuchMethodException: [class android.nfc.NdefRecord]
while on Debugging it shows me everythis correct. I can access indices of my Array. WHY the hell java tells me that ndefRecords are of class NdefRecords instead of NdefRecords[]??
You problem is that the
newInstancemethod is diamond function (i.e. function that takes variable number of parameters):In java, however you can pass in an array to such function and the elements of the array will be considered as consecutive parameters passed in to the function. Thus you get:
And the two calls to the
avgfunction have exactly the same meaning.One quick fix for you I can think of is to change your call to
newInstancewith: