![](/img/trans.png)
[英]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.