简体   繁体   English

是否有可能在Java中模拟Javascript风格的原型?

[英]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. 我想知道是否可以在Java中模拟Javascript原型。 Is it possible to associate a list of variables with a function in Java? 是否可以将变量列表与Java中的函数相关联? I want to create something similar to Javascript prototypes, if that's even possible. 我想创建类似于Javascript原型的东西,如果可能的话。

So here's an example (in Javascript): 所以这是一个例子(在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? 有没有办法在Java中完成相同的操作?

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. 创建一个包含属性Map的类。 This becomes your "Base Object" class for all your prototypes. 这将成为您所有原型的“基础对象”类。 K is probably String, V is probably Object K可能是String,V可能是Object
  • Create getters and setters for your properties 为您的属性创建getter和setter
  • 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.). 它不像在动态语言中直接执行它那样优雅,但它可以工作并获得相同的好处(运行时灵活性,避免严格OOP的约束,快速的proptotyping等)。

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. 举个例子,我写的开源游戏( 暴君 )将这种方法用于所有游戏内对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM