如何使用文字为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 };
要获得Class
表示某些内容的文字,Type
您可以编写Type.class
。
对于数组使用Type[].class
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句