添加构造函数以deftype创建的类 [英] Add constructor to deftype created class

查看:137
本文介绍了添加构造函数以deftype创建的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了与Java的互操作性,我需要一个具有执行初始化的nullary构造函数的类。
这个类的对象需要有类似于可变的java字段的东西(即,对象表示游戏的后端,并且需要保持游戏状态)。

For the purposes of interoperability with Java, I need a class that has a nullary constructor that performs initialization. Objects of this class need to have something resembling mutable java fields (namely, the object represents the backend of a game, and needs to keep game state).

deftype 我想做 除非提供一个nullary构造函数(因为我创建了一个包含字段的类)。

deftype does everything I want to do except provide a nullary constructor (since I'm creating a class with fields).

我不需要字段是公共可读的,所以我可以想到4个解决方案:

I don't need the fields to be publicly readable, so I can think of 4 solutions:

使用gen-我不想这样做,如果我可以避免它。

不知何故编码私人成员变量的知识deftype;我已经被告知这不能做。

编写一个修改的deftype,也创建一个nullary构造函数;坦白说,我不知道Clojure足够这样。

接受由deftype创建的类,并以某种方式添加一个新的构造函数。

Use gen-class; I don't want to do this if I can avoid it.
Somehow encoding private member variables outside of the knowledge of deftype; I've been told this can't be done.
Writing a modified deftype that also creates a nullary constructor; frankly I don't know clojure well enough for this.
Taking the class created by deftype and somehow adding a new constructor to it.

最后,我需要一个Java类,因为我将把它交给Java代码,将从类中创建一个新的对象。

At the end of this, I need to have a Java class, since I will be handing it off to Java code that will be making a new object from the class.

Are任何我建议的解决方案(或任何我没有想过)除了使用gen类可行吗?

Are any of the solutions I suggested (or any that I haven't thought of) other than using gen-class viable?

推荐答案

如果你的Java互操作要求是同时具体和不可动摇的,那么在适当的时候,写一个Java短语是绝对没有可耻的。你可以用一个单独的静态工厂方法写一个Java类,返回一个 deftype 类的实例,并且做任何你需要的初始化/设置。

There's absolutely no shame in, where appropriate, writing a dash of Java if your Java interop requirements are simultaneously specific and unshakable. You could write a Java class with a single static factory method that returns an instance of the deftype class and that does whatever initialization/setup you need.

或者,你可以在Clojure中写一个nullary工厂函数,并直接从Java中调用它。

Alternatively, you can write a nullary factory function in Clojure, and call that directly from Java all day long.

在任何情况下, deftype defrecord 旨在是(或将是)全功能的互操作设施。 gen-class 肯定是最接近的,这就是为什么它被推荐。

In any case, neither deftype nor defrecord are intended to be (or will they ever be) fully-featured interop facilities. gen-class certainly comes the closest, which is why it's been recommended.

这篇关于添加构造函数以deftype创建的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆