从 Java 接口生成 Typescript 接口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32451966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:05:28  来源:igfitidea点击:

Generate Typescript Interfaces from Java Interfaces

javatypescript

提问by jwa

I have a Java server application, which uses Hymanson to generically serialize DTO's using the reflection API. For example for this DTO interface:

我有一个 Java 服务器应用程序,它使用 Hymanson 使用反射 API 一般序列化 DTO。例如对于这个 DTO 接口:

package com.acme.library;
public interface Book { 
  com.acme.library.Author getAuthor();
  String getTitle();
}

From the POJO implementation of this interface, Hymanson will generically serialize the following entity:

从这个接口的 POJO 实现中,Hymanson 将一般序列化以下实体:

{
   "author": { "name": "F. Scott Fitzgerald"},
   "title": "The Great Gatsby"
}

This payload will be recieved using a HTTP GET from my TypeScript application, which is AngularJS-based:

将使用来自我的基于 AngularJS 的 TypeScript 应用程序的 HTTP GET 接收此有效负载:

$http.get("http://localhost/books/0743273567")
   .success((book: Book) => { ... });

So that I am able to use the strongly-typed nature of TypeScript, I find myself hand-coding the following typescript interface:

为了能够使用 TypeScript 的强类型特性,我发现自己手动编写了以下 typescript 接口:

module com.acme.library {
  export interface Book {
      author: com.acme.library.Author;
      title: String;
  }
}

As a result, I have to maintain two copies of this same interface -- which is cumbersome at best. This gets particularly nasty, as I'd like to have the same javadoc/jsdoc comments on both interfaces, which involves a whole heap of copy&paste.

结果,我必须维护同一个界面的两个副本——这充其量是很麻烦的。这变得特别令人讨厌,因为我希望在两个接口上都有相同的 javadoc/jsdoc 注释,这涉及到大量的复​​制和粘贴。



I would like to find a mechanism for automating this process.

我想找到一种机制来自动化这个过程。

Java is my main development language. As such, I'd like to find some tool which is capable of converting from the Java interface declaration (via the reflection API?) to the relevant TypeScript interface.

Java 是我的主要开发语言。因此,我想找到一些能够从 Java 接口声明(通过反射 API?)转换为相关 TypeScript 接口的工具。

The only tool I have discovered in this domain is the NPM package ts-java. However, this is far too heavyweight for my use-case. It adds methods from the Object hierarchy to each interface, e.g. hashCode(), wait(), getClass(), etc.

我在这个领域发现的唯一工具是 NPM 包ts-java。但是,这对于我的用例来说太重了。它增加了从对象层次结构的方法给每个接口,例如hashCode()wait()getClass()等。

回答by Vojta

You can use typescript-generatoras larslonne mentioned. It generates TypeScript interfaces from Java JSON classes. Some features you may find useful:

您可以使用typescript -generator作为 larslonne 提到的。它从 Java JSON 类生成 TypeScript 接口。您可能会发现一些有用的功能:

  • Maven and Gradle plugin (can also be invoked directly from Java)
  • Hymanson 1 and Hymanson 2
  • collections, enums, inheritance, generics
  • Javadoc comments to JSDoc comments
  • detailed documentation (README, Wiki, Maven plugin)
  • releases in Maven central repo
  • Maven 和 Gradle 插件(也可以直接从 Java 调用)
  • Hyman逊 1 和Hyman逊 2
  • 集合、枚举、继承、泛型
  • Javadoc 注释到 JSDoc 注释
  • 详细文档(README、Wiki、Maven 插件)
  • 在 Maven 中央仓库中发布

Here is example how to use it from Maven:

以下是如何从 Maven 使用它的示例:

<plugin>
    <groupId>cz.habarta.typescript-generator</groupId>
    <artifactId>typescript-generator-maven-plugin</artifactId>
    <version>1.25.322</version>
    <executions>
        <execution>
            <id>generate</id>
            <goals>
                <goal>generate</goal>
            </goals>
            <phase>process-classes</phase>
            <configuration>
                <jsonLibrary>Hymanson2</jsonLibrary>
                <classes>
                    <class>com.acme.library.Book</class>
                </classes>
                <outputFile>target/rest.d.ts</outputFile>
                <outputKind>module</outputKind>
            </configuration>
        </execution>
    </executions>
</plugin>

Edit: Run it using mvn process-classesor using later phase like mvn install.
You can also pull <configuration>element two levels up and run mvn typescript-generator:generate.

编辑:使用mvn process-classes或使用以后的阶段运行它,如mvn install.
您还可以将<configuration>element拉上两个级别并运行mvn typescript-generator:generate

Edit: I am the author of typescript-generator.

编辑:我是 typescript-generator 的作者。

回答by Ryan Weir

I had great luck with Amdatu TypeScript Generator

我很幸运使用Amdatu TypeScript Generator

It can run in Gradle or standalone from the terminal (I used terminal, so that's what these instructions here are)

它可以在 Gradle 中运行或从终端独立运行(我使用终端,所以这就是这里的这些说明)

Simply clone the repo, run ./gradlewto build it.

只需克隆 repo,运行./gradlew即可构建它。

To execute it, I had to deviate a little from their instructions because there was no entry point in the jar (you wouldn't have this issue if you use a gradle build, because it would specify the entry class).

为了执行它,我不得不稍微偏离他们的说明,因为 jar 中没有入口点(如果使用 gradle 构建,则不会出现此问题,因为它会指定入口类)。

I used:

我用了:

java -cp build/libs/org.amdatu.typescriptgenerator-1.0-SNAPSHOT.jar org.amdatu.typescriptgenerator.standalone.TypeScriptGeneratorStarter

It should then complain that there isn't a typescript.settings.jsonfile, which it's expecting in the directory you are running the command from.

然后它应该抱怨没有typescript.settings.json文件,它期望在您运行命令的目录中。

I'll include my own example because the linked repo's example settings file is a little unclear:

我将包含我自己的示例,因为链接存储库的示例设置文件有点不清楚:

{
  "folder" : "/projectsfolder/project",
  "classFolder" : "target/classes",
  "output" : "typscriptOutputDirectory",
  "baseFolder" : "",
  "clearOutput" : false,
  "packages" : [
    ".*regexforwhatpackagesinsidetargetprojectshouldbeturnedintotypescript.*"
  ],
  "excludePackages" : [ ],
  "excludePattern" : [ ],
  "types" : { },
  "mapping" : { },
  "enumType" : "class",
  "classType" : "interface",
  "classPath" : [ ]
}

The most important fields in the settings are:

设置中最重要的字段是:

  • folderis where your already builtproject is
  • classFolderis where this generator will look inside that folder for compiled java classes
  • outputis the directory where the typescript definition files will be placed, relative to where you're executing the generator
  • packagesis a java regex for what packages should be turned into TypeScript definitions
  • folder是您已经构建的项目所在的位置
  • classFolder是此生成器将在该文件夹中查看已编译 Java 类的位置
  • output是放置打字稿定义文件的目录,相对于您执行生成器的位置
  • packages是一个 java 正则表达式,用于说明哪些包应该转换为 TypeScript 定义

回答by lalo

I am currently working on a project with the same setup as yours: a Java API, and a Typescript web application.

我目前正在开发一个与您具有相同设置的项目:Java API 和 Typescript Web 应用程序。

We are using cz.habarta.typescript-generator.typescript-generator-maven-pluginto generate the .d.tsfiles when we build the API. The definition files are then packaged as an artifact with <type>d.ts</type>, using the org.codehaus.mojo.build-helper-maven-plugin. Lastly, the artifact is imported as a dependency in the web application, where the definition files are unpacked into the targetdirectory.

我们在构建 API 时使用它cz.habarta.typescript-generator.typescript-generator-maven-plugin来生成.d.ts文件。然后<type>d.ts</type>使用org.codehaus.mojo.build-helper-maven-plugin. 最后,工件作为 Web 应用程序中的依赖项导入,其中定义文件被解压到target目录中。

This setup requires that you use maven for the web application, which isn't ideal, but it's a small price to pay for automatically generated definition files.

此设置要求您将 maven 用于 Web 应用程序,这并不理想,但为自动生成的定义文件付出的代价很小。

回答by firegloves

I created a new project with the goal to keep as simple as possible the transpiling process: JavaModel-Converter

我创建了一个新项目,目的是使转译过程尽可能简单:JavaModel-Converter

It works with the ide or simply by command line executing the jar present into dist folder.

它可以与 ide 一起使用,或者只是通过命令行将存在的 jar 执行到 dist 文件夹中。

All you need is to put your java model in the desired folder and to start transpile process.

您所需要的只是将您的 java 模型放在所需的文件夹中并开始转换过程。

I added also Angular style support.

我还添加了 Angular 样式支持。

Let's open issues if you have requests!

如果您有要求,让我们打开问题!

Theoretically my project is a general java model converter, but actually, only Typescript transpile is supported

理论上我的项目是一个通用的java模型转换器,但实际上,只支持Typescript transpile

回答by wizawu

As such, I'd like to find some tool which is capable of converting from the Java interface declaration (via the reflection API?) to the relevant TypeScript interface.

因此,我想找到一些能够从 Java 接口声明(通过反射 API?)转换为相关 TypeScript 接口的工具。

You can first have a look at these samples. I didn't port the java -> typescriptfunction to a stand-alone CLI tool (from the whole project) but it is easy to do that.

您可以先看看这些示例。我没有将java -> typescript函数移植到独立的 CLI 工具(来自整个项目),但很容易做到这一点。

回答by Pavel_K

You can use Script4Jthat is a set of libraries to code in TypeScript using Java API. Although this is a new project it can be useful.

您可以使用Script4J,它是一组使用 Java API 在 TypeScript 中编码的库。虽然这是一个新项目,但它可能很有用。