我正在尝试模拟一种在另一种晦涩的编程范式中使用的指针,这样我就可以将一些代码移植到 Java 中。另一种语言不是面向对象的,并大致受到 Pascal 的启发。
在原始语言中,我们可以这样写代码。首先,处理文本。
// Start with text.
Text myVar = "Bonjour"
Pointer myPointer = ->myVar // Referencing a string variable, storing the reference in another variable of type `Pointer`.
Message( myPointer-> ) // Dereferencing the pointer, to retrieve `myVar`, and pass the string to a command `Display` that displays the message on screen in a dialog box.
然后,切换到数字。
// Switch gears, to work with an number.
Integer vResult = ( Random % ( vEnd - vStart + 1 ) ) + vStart // Generate random number.
myPointer = ->vResult // The same pointer now points to numeric variable rather than a textual variable.
我们可以通过变量名的文本来分配一个指针。
myPointer = Get pointer( "var" + String($i) ) // Generate pointer variable named `var1`, or `var2`, etc.
我们可以向指针请求一个代码编号,该编号表示它所指向的值的数据类型(所指对象的数据类型)。
typeCodeNumber = Type( myPointer ) // Returns 11 for an integer, 22 for text.
在这种其他语言中,编译器确实提供了type-safety .但是当以这种方式使用指针时,我们牺牲了类型安全。编译器发出警告,指出代码使用类型不明确。
移植此代码的想法是定义一个 XPointer
类以及用于 XText
和 XInteger
等类型的类。
我需要持有一个对一打特定已知类型中任何一个的对象的引用,包括对另一个指针的引用。我可以硬编码十几种类型,不需要对所有类型开放。
除Object
外,这十几种类型不共享接口(interface)或抽象类。 .即使它们确实共享一个接口(interface)/父类(super class),我也不希望它们作为父类(super class)返回,而是作为它们原始的具体类返回。当它们进入指针时,它们也应该从指针中出来。
我目前的计划是用一对引用和取消引用方法在Java中定义一个XPointer
类:
XPointer::ref( x )
在其中传递Dog
、Truck
或Sculpture
对象类,甚至是另一个XPointer
对象。XPointer::deref ⇒ x
其中 x 是被识别为其原始类型的对象,Dog
、Truck
或Sculpture
甚至另一个XPointer
对象,而不仅仅是一个Object
对象。
➥ Java 有什么办法吗?也许用 Generics ?
➥ 如果在 Java 中不行,我可以不情愿地切换到 Kotlin。这个指针功能可以在Kotlin中完成吗?在 JVM 上运行?
所以我的代码如下:
XPointer p = new XPointer() ; // Points to nothing, null.
p.ref( new Dog() ) ; // Pointer points to a `Dog` object.
p.deref().bark() ; // Pointer can retrieve the `Dog` as such, a `Dog` object.
p.ref( someTruck ) ; // The pointer can switch to pointing to an object of an entirely different type. The `Dog` object has been replaced by a `Truck` object.
p.deref().honk() ; // Dereference the stored `Truck` object as such.
还有一个指向指针的指针。
XPointer p2 = new XPointer() ; // Points to nothing, null.
p2.ref( p ) ; // 2nd pointer points to a pointer that points to a `Truck` object.
p2.deref().deref().honk() ; // Dereference the stored `Truck` object as such.
如果有更好的指针模拟方法,我愿意接受建议。不需要优雅;任何黑客都可以。
最佳答案
这被称为联合 或变体 类型(参见 C++ 中的 Boost.Variant)。后者特别方便,因为它是异构类型集的类型安全容器,并且最接近您对要从中移植的代码类型的描述。由于 Java 不支持模板 - no, generics are not templates - 你不会得到你正在寻找的东西。
Optional 类型是两种类型中最简单的情况:类型 T 和 Null。考虑到您需要存储超过类型 T 或 Null 的内容,它对您不起作用。
您可能想查看 JavaSealedUnions .另外,Kotlin 提供了一个概念 sealed classes ,有助于将值限制为受限集中的一种类型。
祝你好运!
关于java - 用Java模拟一个指针?在 Kotlin ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54860458/