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.
Yes, if you are using Java 8 or above. Java 8 make it possible to define anonymous functions, which was impossible in previous versions.
In Python, an anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions.
Anonymous functions, also known as closures , allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses. Anonymous functions are implemented using the Closure class.
Lambda Expressions are anonymous functions. These functions do not need a name or a class to be used. Lambda expressions are added in Java 8. Lambda expressions basically express instances of functional interfaces An interface with a single abstract method is called a functional interface.
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!
}
}
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();
}
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With