我想知道是否有一些方法来创建一个方法数组来调用这个数组代替下面例子中的方法我创建了一个数组,在这个类中存储用户对象有getName方法,我想通过数组调用此方法,如下例子:
public class JavaApplication48 {
public static void main(String[] args) {
User[] u = new User[] {new User ("1", "John"), new User ("2", "Tereza"), new User ("3", "Tobias")};
//there put the methods .getId() and .getName in a array, i dont know who
//...
//and concatenating the users array with methods array like this
System.out.println(u[0]ac[1]);
//to print on the console "John"
}
}
class User {
private String id;
private String name;
public User(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
}
答案 0 :(得分:1)
你可以使用lambda表达式来解决这个问题:
public static void main(String[] args) {
User[] u = new User[] {new User ("1", "John"), new User ("2", "Tereza"), new User ("3", "Tobias")};
Function<User, String> f1 = user -> user.getName();
Function<User, String> f2 = user -> user.getId();
Function<User, String>[] f = new Function[] { f1, f2 };
System.out.println(f[0].apply(u[0]));
}
(我不明白你想用这个来实现什么,但这在技术上是可行的。)
我们声明的函数在它们的接口中声明了一个方法“apply”,因此你在System.out-line中看到的最终调用是
functionReference.apply(inputObject)