java中的匿名函数

Jag*_*Jag 5 java anonymous-function

我有一个名为LinkGroup的类,它包含一些游戏对象.我调用Rotate为这些对象设置一些旋转变量.每当我的游戏到达其更新循环时,我会根据旋转变量旋转对象.如果它们旋转得足够多,我会触发onComplete回调.

以下代码有效......

public void Rotate(){
    _currentRotation = _0;
    _targetRotation = 180; //degrees
    _rotationSpeed = 50;

    try{
        _onComplete = LinkGroup.class.getDeclaredMethod("rotateComplete", null);
    }
    catch(Exception ex){

    }
}
Run Code Online (Sandbox Code Playgroud)

......但这很难看.

我不喜欢声明方法rotateComplete并手动将其链接到通过字符串旋转.是否有类似于C#中的匿名函数,所以我可以在Rotate方法中声明rotateComplete方法?

对于奖励积分,有没有更好的方法来实现"getDeclaredMethod"所需的异常处理?Terseness是一种偏好.

Shi*_*vam 7

根据我的理解,我相信你试图在某个游戏对象被旋转时onRotateComplete()LinkGroup类中调用方法.您可以使用Java Swing用于处理按钮单击或其他事件的模式:这可以通过以下方式完成:

定义一个接口

interface IRotateHandler {
    public void onRotateComplete();
}
Run Code Online (Sandbox Code Playgroud)

更改为Rotate()to Rotate(IRotateHandler handler)然后在LinkGroup课堂上你可以像这样调用你的游戏对象.

gameObject.Rotate(new IRotateHandler() {
    public void onRotateComplete() {
        /* do your stuff!
    }
}
Run Code Online (Sandbox Code Playgroud)