【发布时间】:2019-07-18 12:25:44
【问题描述】:
我正在尝试模拟另一种晦涩的编程范例中使用的一种指针,因此我可以将一些代码移植到 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 之外,这十几个类型不共享接口或抽象类。即使它们确实共享一个接口/超类,我也不希望它们作为超类返回,而是作为它们原来的具体类返回。当他们进入指针时,他们应该从指针中出现。
我目前的计划是用一对 reference 和 dereference 方法在 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.
如果有更好的方法实现这种指针模拟,我愿意接受建议。不需要优雅;任何黑客都可以。
【问题讨论】:
-
Optional<T>够好吗?或者可能是Deque<T>。 -
@ElliottFrisch 我熟悉
Optional用于发出possible null in a return value 的信号。但我看不到它在这里如何应用?Pointer::ref方法看起来如何? -
其实一个字段的数组就像一个指针。
-
@kai 但是数组必须有特定的类型。如何将对象作为其原始具体类型返回?请注意,在我的示例代码中,我如何从在同一指针中存储
Dog切换到存储Truck,但能够将狗返回为Dog,将卡车返回为Truck。 -
一个数组在 Java 中有一个类型,它是 YourType[] ptr = {yourobject};这相当于 C: YourType * ptr = &yourobject;