Jag
Jag

Reputation: 1870

Anonymous functions in java

I have a class called LinkGroup which holds some game objects. I call Rotate to set some rotation variables for these objects. Whenever my game hits its update loop, I rotate the objects according to the rotation variables. If they've rotated enough, I fire an onComplete callback.

The following code works...

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

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

    }
}

...but this is ugly.

I don't like having to declare the method rotateComplete and manually link it to Rotate via a string. Is there something similar to anonymous functions in C# so I can just declared the rotateComplete method inside the Rotate method?

For bonus points, is there a better way to implement the required exception handling for "getDeclaredMethod"? Terseness is a preference.

Upvotes: 5

Views: 3555

Answers (3)

Shivam
Shivam

Reputation: 2132

From my understanding, I believe you are trying to call onRotateComplete() method in the LinkGroup class whenever some game object is been rotated. You can use the pattern that Java Swing uses for handling button clicks or other events: This could be done this way:

Define an interface

interface IRotateHandler {
    public void onRotateComplete();
}

Change the Rotate() to Rotate(IRotateHandler handler) and then in LinkGroup class you can call your game object like this.

gameObject.Rotate(new IRotateHandler() {
    public void onRotateComplete() {
        /* do your stuff!
    }
}

Upvotes: 8

Mankarse
Mankarse

Reputation: 40633

You don't need to use getDeclaredMethod. Just make _onComplete be a Runnable (or something similar), and create an anonymous class:

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

    _onComplete = new Runnable() {
            public void run() {
                rotateComplete();
            }
        };
}

Upvotes: 4

Makoto
Makoto

Reputation: 106460

Java 7 doesn't yet have closures. Java 8 will. So, for the time being, there's no way to write that function anonymously in Java.

As for the error handling, a quick glance at the API shows me that you throw two RuntimeExceptions and a ReflectiveOperationException. Catching Exception may be your best bet, unless you wanted to catch all three of these possible exceptions differently, and take different action based on each.

Upvotes: 0

Related Questions