Maven Mojo Mapping Complex Objects

2019-05-14 06:41发布

问题:

I'm trying to write a maven plugin, including a mapping of a custom class in mvn configuration parameters. Does anybody know how the equivalent class "Person" would look like: http://maven.apache.org/guides/mini/guide-configuring-plugins.html#Mapping_Complex_Objects

<configuration>
     <person>
          <firstName>Jason</firstName>
          <lastName>van Zyl</lastName>
     </person>
</configuration>

My custom mojo looks like that:

/**
 * @parameter property="person"
 */
protected Person person;
public class Person {
    protected String firstName;
    protected String lastName;
}

but I always get the following error: Unable to parse configuration of mojo ... for parameter person: Cannot create instance of class ...$Person

Can anybody help me?


EDIT:

Mojo class with Person (including default constructor, getter & setter) as inner class.

public class BaseMojo extends AbstractMojo {

/**
 * @parameter property="ios.person"
 */
protected Person person;

public class Person {
    /**
     * @parameter property="ios.firstName"
     */
    protected String firstName;

    /**
     * @parameter property="ios.lastName"
     */
    protected String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Person() {

    }
}

回答1:

If using an inner class it needs to be static so it can initiated without having to create the outer class first. Inner classes are useful if it's created using private variables from the outer class but maven just's not doing that.

Hopefully the below example helps explain why it won't work...

public class ExampleClass {
    public class InnerInstance {}

    public static class InnerStatic {}

    public static void main(String[] args) {
      // look, we have to create the outer class first (maven doesn't know it has to do that)
      new ExampleClass().new InnerInstance();

      // look, we've made it without needing to create the outer class first
      new ExampleClass.InnerStatic();

      // mavens trying to do something like this at runtime which is a compile error at compile time
      new ExampleClass.InnerInstance();
    }
}