[英]How to call instance method in predefined class from another class in android
[英]Build method call from class instance and string?
在Java中,是否可以在给定类实例的情况下执行方法调用,并将该方法调用另存为字符串?
我想将一系列不同的方法调用随机化,因此我打算将方法部分作为字符串放置在列表中,然后将它们洗牌。 然后,如何使用此字符串作为方法调用的一部分? 例如,下面的myClass.temp被视为属性。 如果我填写完整的myClams。 在列表中作为对象,它将尝试在那里执行它们。
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
这是一个糟糕的方法。 而是创建一个Runnable或Callable对象的列表,对列表进行随机组合,然后调用runnable:
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();
}
使用Java 8,该代码将成为
MyClass myClass = ...;
List<Runnable> actions = new ArrayList<>();
actions.add(() -> myClass.createMethodx(...));
actions.add(() -> myClass.createMethody(...));
Collections.shuffle(actions);
for (Runnable action : actions) {
action.run();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.