我只想知道这是否可能。我已经使用Javascript四年作为一个Web开发人员,所以我非常习惯在我的代码中使用匿名函数。现在正在测试Processing,我想看看如何通过Javascript来完成所有我通常做的事情。Java处理,使用匿名函数
在Javascript中,我使用的功能,像这样:
fn.call(instance,arg1, arg2);
或
fn.apply(instance,args);
...但是,我不能做这样的事情在处理。
我试图调用一个“匿名函数”,并在实例的命名空间中运行函数:
public void resetHealth(){
this.health = 10;
}
class Player{
public int health;
Player(){
super();
this.health = 10;
}
}
Player p = new Player();
//where it gets prickly:
resetHealth.invoke(p);
预期结果:print p.health; //returns 0
我想知道什么,我Java的做法是错误的。但是,它可能与处理有关。
为什么resetHealth是Player类之外的函数?现在这个方法没有上下文或含义。 –
原因是我可以共享函数并将它们传递给它们,而不是将函数放入类中。有没有办法做到这一点? –
请参阅Java 8 [方法参考](https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html)。但我鼓励你简单地定义[interfaces](https://docs.oracle.com/javase/tutorial/java/concepts/interface.html),并传递实现该接口的对象。 “把方法放在物体内”是好的:) – paulsm4