如何使用文字来定义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 };
答案 0 :(得分:1)
要获得代表某些Class
的{{1}}字面值,您可以撰写Type
。
对于数组,请使用Type.class
。