Reputation: 31840
I'd like to know whether it's possible to simulate Javascript prototypes in Java. Is it possible to associate a list of variables with a function in Java? I want to create something similar to Javascript prototypes, if that's even possible.
So here's an example (in Javascript):
var s = doStuff.prototype;
s.isImplemented = false;
function doStuff(){
//this function has not yet been implemented
}
var s = functionIsImplemented.prototype;
s.isImplemented = true;
function functionIsImplemented(theFunction){
//this function returns true if the function has been identified as "implemented"
if(theFunction.prototype.isImplemented == true){
return true;
}
return false;
}
alert(functionIsImplemented(doStuff)); //this should print "false"
alert(functionIsImplemented(functionIsImplemented)); //this should print "true"
Is there any way to do the equivalent of this in Java?
Upvotes: 3
Views: 404
Reputation: 106391
Yes, it's certainly possible, and can be very useful for some situations.
Typically you would do the following:
It's not as elegant as if you do this directly in a dynamic language, but it works and gets you the same benefits (runtime flexibility, avoid constraints of rigid OOP, fast proptotyping etc.).
It also has the same downsides - loss of static type checking and some performance overhead being the main ones.
As an example, the open source game I wrote (Tyrant) uses this approach for all the in-game objects.
Upvotes: 4