0
如何使用文字爲java.lang.Class.getMethod定義參數類型?如何爲任意類的數組的類編寫文字
public class NewTester
{
public static void main(String[] args)
{
System.out.println("START");
Worker myWorker = new Worker();
Thing[] argument = new Thing[] { new Thing("book"),
new Thing("pencil") };
Object[] arguments = new Object[] { argument };
// HOW ABOUT LITERALS HERE INSTEAD OF getClass
Class<?>[] parameterTypes = new Class<?>[] { argument.getClass() };
Method myMethod;
try
{
myMethod = myWorker.getClass().getMethod("work", parameterTypes);
}
catch (NoSuchMethodException | SecurityException e)
{
throw new RuntimeException(e);
}
try
{
myMethod.invoke(myWorker, arguments);
}
catch (IllegalAccessException |
IllegalArgumentException |
InvocationTargetException e)
{
throw new RuntimeException(e);
}
System.out.println("END");
}
private static class Worker
{
@SuppressWarnings("unused")
public void work(Thing[] argument)
{
assert argument.length == 2;
assert argument[0].value.equals("book");
assert argument[1].value.equals("pencil");
}
}
private static class Thing
{
String value;
Thing(String value)
{
this.value = value;
}
}
}
我嘗試了以下方法,但是在使用NoSuchMethodException的getMethod調用中失敗。
Class<?>[] parameterTypes = new Class<?>[] { java.lang.reflect.Array.class };
我不知道我是否理解你的問題,但看起來你可能正在尋找'Thing [] .class'。 – Pshemo
是的。謝謝。我不認爲這是可行的,因爲我強制使用括號。 '(Thing []).class'沒有編譯。你的確如此。 – H2ONaCl