带有javac"-parameters"的JSON ObjectMapper在通过maven运行时表现,而不是通过InteliJ IDEA运行

Mik*_*kis 2 java json javac intellij-idea maven

你可以从标题中收集,这是一个有点复杂的问题.

首先,我的目标:

  • 我试图实现我的Java类与JSON之间的转换,而不必向它们添加任何特定于json的注释.

  • 我的java类包括immutables,它必须从传递给构造函数的参数初始化它们的成员,所以我必须有多参数构造函数,它们在没有@JsonCreator且没有@JsonParameter的情况下工作.

  • 我正在使用jackson ObjectMapper.如果我可以使用的另一个ObjectMapper没有这里描述的问题,我会很乐意使用它,但它必须与jackson ObjectMapper 一样有信誉.(所以,我不愿意从他的GitHub下载Jim的ObjectMapper.)

我理解如何实现这一点,以防万一我错了:

Java用于使方法(和构造函数)参数类型可通过反射发现,但不能通过参数名称发现.这就是为什么@JsonCreator和@JsonParameter注释过去是必要的:告诉json ObjectMapper哪个构造函数参数对应于哪个属性.使用Java 8,如果提供新-parameters参数,编译器会将方法(和构造函数)参数名称发送到字节码中,并通过反射使它们可用,并且最近版本的jackson ObjectMapper支持这一点,因此现在应该可以拥有json对象映射,没有任何特定于json的注释.

我有这个pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>test</groupId>
    <artifactId>test.json</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>Json Test</name>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <build>
        <sourceDirectory>main</sourceDirectory>
        <testSourceDirectory>test</testSourceDirectory>
        <plugins>
            <plugin>
                <!--<groupId>org.apache.maven.plugins</groupId>-->
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <!--<compilerArgument>-parameters</compilerArgument>-->
                    <!--<fork>true</fork>-->
                    <compilerArgs>
                        <arg>-parameters</arg>
                    </compilerArgs>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-json-provider</artifactId>
            <version>2.7.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-parameter-names</artifactId>
            <version>2.7.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>
Run Code Online (Sandbox Code Playgroud)

我用它来编译和运行以下小的自包含程序:

package jsontest;

import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;

import java.io.IOException;
import java.lang.reflect.*;

public final class MyMain
{
    public static void main( String[] args ) throws IOException, NoSuchMethodException
    {
        Method m = MyMain.class.getMethod("main", String[].class);
        Parameter mp = m.getParameters()[0];
        if( !mp.isNamePresent() || !mp.getName().equals("args") )
            throw new RuntimeException();
        Constructor<MyMain> c = MyMain.class.getConstructor(String.class,String.class);
        Parameter m2p0 = c.getParameters()[0];
        if( !m2p0.isNamePresent() || !m2p0.getName().equals("s1") )
            throw new RuntimeException();
        Parameter m2p1 = c.getParameters()[1];
        if( !m2p1.isNamePresent() || !m2p1.getName().equals("s2") )
            throw new RuntimeException();

        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule( new ParameterNamesModule() ); // "-parameters" option must be passed to the java compiler for this to work.
        mapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true );
        mapper.configure( SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true );
        mapper.setSerializationInclusion( JsonInclude.Include.ALWAYS );
        mapper.setVisibility( PropertyAccessor.ALL, JsonAutoDetect.Visibility.PUBLIC_ONLY );
        mapper.enableDefaultTyping( ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY );

        MyMain t = new MyMain( "1", "2" );
        String json = mapper.writeValueAsString( t );
        /*
         * Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class saganaki.Test]: can not
         * instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
         */
        t = mapper.readValue( json, MyMain.class );
        if( !t.s1.equals( "1" ) || !t.s2.equals( "2" ) )
            throw new RuntimeException();
        System.out.println( "Success!" );
    }

    public final String s1;
    public final String s2;

    public MyMain( String s1, String s2 )
    {
        this.s1 = s1;
        this.s2 = s2;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是发生的事情:

  • 如果我使用编译程序mvn clean compile然后在Idea中运行或调试它,它工作正常,它显示"成功!".

  • 如果我从Intellij Idea中执行"Rebuild Project",然后运行/ debug,则会失败并JsonMappingException显示"找不到简单类型jsontest.MyMain的合适构造函数".

  • 奇怪的是(对我来说)是,ObjectMapper实例化之前的代码检查以确保构造函数参数名称存在且有效,有效地确保"-parameters"参数已成功传递给编译器,并且这些检查总是过去!

  • 如果我在Idea中编辑我的"调试配置"并在"发布之前"部分中删除"Make"并将其替换为"Run maven goal" compile然后我可以在Idea中成功运行我的程序,但我不想必须这样做. (而且,它甚至不能很好地工作,我想我一定是做错了:我经常运行并且它失败并且上面的例外情况相同,下次我运行它会成功.)

所以,这是我的问题:

  • 为什么我的程序在使用maven编译时的行为与使用Idea编译时的行为不同?

    • 更具体地说:什么是ObjectMapper的问题,因为我的断言证明"-parameters"参数传递给编译器,而参数确实有名字?
  • 我能做些什么才能使Idea以与maven相同的方式编译我的程序(至少就手头的问题而言)而不替换Idea的"Make"?

  • 当我compile在Idea的调试配置中将默认的"Make"替换为"Run maven goal"时,为什么它不能始终如一?(我究竟做错了什么?)

编辑

我很抱歉,assert离子并不一定能证明什么,因为它们不一定能够实现-enableassertions.我替换它们if() throw RuntimeException()以避免混淆.

Jes*_*sen 5

据我所知,在IntelliJ社区版源中,IntelliJ没有对compilerArgs你指定的内容做任何事情.

MavenProject.java中,有两个地方compilerArgs被读取:

Element compilerArguments = compilerConfiguration.getChild("compilerArgs");
if (compilerArguments != null) {
  for (Element element : compilerArguments.getChildren()) {
    String arg = element.getValue();
    if ("-proc:none".equals(arg)) {
      return ProcMode.NONE;
    }
    if ("-proc:only".equals(arg)) {
      return ProcMode.ONLY;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Element compilerArgs = compilerConfig.getChild("compilerArgs");
if (compilerArgs != null) {
  for (Element e : compilerArgs.getChildren()) {
    if (!StringUtil.equals(e.getName(), "arg")) continue;
    String arg = e.getTextTrim();
    addAnnotationProcessorOption(arg, res);
  }
}
Run Code Online (Sandbox Code Playgroud)

第一个代码块只查看-proc:参数,因此可以忽略此块.第二个是将arg元素(您指定的)的值传递给addAnnotationProcessorOption方法.

private static void addAnnotationProcessorOption(String compilerArg, Map<String, String> optionsMap) {
  if (compilerArg == null || compilerArg.trim().isEmpty()) return;

  if (compilerArg.startsWith("-A")) {
    int idx = compilerArg.indexOf('=', 3);
    if (idx >= 0) {
      optionsMap.put(compilerArg.substring(2, idx), compilerArg.substring(idx + 1));
    } else {
      optionsMap.put(compilerArg.substring(2), "");
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

此方法仅处理以...开头的参数,-A用于将选项传递给注释处理器.其他参数被忽略.

目前,从IntelliJ中运行源的唯一方法是在编译器设置的"附加命令行参数"字段(不可移植)中自己启用标志,或者通过编译maven作为预先在运行配置中执行步骤.如果您希望在IntelliJ中自动执行此操作,则可能必须向Jetbrains提出问题.