我想使用带有反射的 NdefRecord 实例化 NdefMessage。下面是一个简单的代码 fragment ,它确实应该工作,但没有:
// 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());
我绝对想不到这会失败,收到以下错误消息:
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
所以我得到了正确识别的构造函数。如果我尝试像这样得到它:
Constructor<?> const = ndefMessageClass.getConstructor(ndefRecords[0].getClass())
我明白
04-16 15:44:59.621: W/System.err(14033): java.lang.NoSuchMethodException: [class android.nfc.NdefRecord]
在调试时,它向我显示一切都是正确的。我可以访问数组的索引。为什么java告诉我ndefRecords是NdefRecords类而不是NdefRecords[]??
最佳答案
您的问题是 newInstance
method是菱形函数(即采用可变数量参数的函数):
public T newInstance(Object... initargs)
但是在java中,您可以将数组传递给此类函数,并且数组的元素将被视为传递给函数的连续参数。这样你就得到:
public static void main (String [] args)
{
double [] a = {1.1, 2.2, 4.4};
System.out.println(avg(a) == avg(1.1, 2.2, 4.4));
}
static double avg (double ... numbers)
{
double total = 0;
for (int i = 0; i < numbers.length; i++)
total += numbers [i];
return total / numbers.length;
}
并且对avg
函数的两次调用具有完全相同的含义。
我能想到的一个快速修复方法是将您对 newInstance
的调用更改为:
Object myNdefMessage = const.newInstance(new Object[] {ndefRecords});
关于java - Android对NdefMessage构建失败的反射(reflection),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10175386/