简体   繁体   English

从类实例和字符串构建方法调用?

[英]Build method call from class instance and string?

In Java is it possible to execute a method call given the class instance and the method call saved as a string? 在Java中,是否可以在给定类实例的情况下执行方法调用,并将该方法调用另存为字符串?

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. 例如,下面的myClass.temp被视为属性。 If I put the full myClaims. 如果我填写完整的myClams。 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: 而是创建一个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();
}

With Java 8, that code would become 使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM