Anderson Green
Anderson Green

Reputation: 31840

Is it possible to simulate Javascript-style prototypes in Java?

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

Answers (1)

mikera
mikera

Reputation: 106391

Yes, it's certainly possible, and can be very useful for some situations.

Typically you would do the following:

  • Create a class that contains a Map of properties. This becomes your "Base Object" class for all your prototypes. K is probably String, V is probably Object
  • Create getters and setters for your properties
  • Optionally add other utility methods, for example checking if a function is implemented basically means checking of the property map contains a specific key
  • Implement prototype-based inheritance by either cloning the property map of another object or (more complex) keeping a reference back to the original object
  • Use function objects of some sort to allow the storage of arbitrary code within properties

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

Related Questions