In Java is it possible to execute a method call given the class instance and the method call saved as a string?
I want to make a sequence of different method calls random so I was going to put the method parts in a list as Strings and shuffle them. How do I then use this string as part of a method call? eg myClass.temp below is being treated as a property. If I put the full myClaims. in the List as Objects it will try to execute them there.
List<String> methodList = new ArrayList<String>()
methodList.add("createMethodx(params...)")
methodList.add("createMethody(params...)")
methodList.add("insertMethodz(params...)")
String temp = methodList.get(0)
myClass.temp //Execute the method.....doesn't work
That's a bad way of doing it. Instead, create a list of Runnable or Callable objects, shuffle that list, and then call the runnables:
final MyClass myClass = ...;
List<Runnable> actions = new ArrayList<>();
actions.add(new Runnable() {
public void run() {
myClass.createMethodx(...);
}
});
actions.add(new Runnable() {
public void run() {
myClass.createMethody(...);
}
});
Collections.shuffle(actions);
for (Runnable action : actions) {
action.run();
}
With Java 8, that code would become
MyClass myClass = ...;
List<Runnable> actions = new ArrayList<>();
actions.add(() -> myClass.createMethodx(...));
actions.add(() -> myClass.createMethody(...));
Collections.shuffle(actions);
for (Runnable action : actions) {
action.run();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.