How do I use literals to define parameter types for 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;
}
}
}
I tried the following but it fails in the getMethod call with a NoSuchMethodException.
Class<?>[] parameterTypes = new Class<?>[] { java.lang.reflect.Array.class };
Aucun commentaire:
Enregistrer un commentaire