3

嗨,我在 Netbeans 平台中的模块设计有问题。

我的例子解释了这个问题:

我的项目:

Test-API (API module)
  SP1 (ServiceProvider interface)
  SP2 (ServiceProvider interface)

Test-Module1
  SP1Impl (ServiceProvider class implements SP1)

Test-Module2
  SP2Impl (ServiceProvider class implements SP2)

Test-Module3
  TestAction

SP1:

package linkagetest.api;

import org.jdom2.Element;

public interface SP1 {
  public Element create();
}

SP2:

package linkagetest.api;

import org.jdom2.Element;

public interface SP2 {
  public void doStuff(Element element);
}

SP1Impl:

package linkagetest.mod1;

import linkagetest.api.SP1;
import org.jdom2.Element;
import org.openide.util.lookup.ServiceProvider;

@ServiceProvider(service = SP1.class)
public class SP1Impl implements SP1 {

  @Override
  public Element create() {
    return new Element("BLA");
  }
}

SP2Impl:

package linkagetest.mod2;

import linkagetest.api.SP2;
import org.jdom2.Element;
import org.openide.util.lookup.ServiceProvider;

@ServiceProvider(service = SP2.class)
public class SP2Impl implements SP2 {

  @Override
  public void doStuff(Element element) {
    element.addContent(new Element("BLA"));
  }
}

测试动作:

package linkagetest.mod3;

import linkagetest.api.SP1;
import linkagetest.api.SP2;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.Lookup;
import org.openide.util.NbBundle.Messages;

@ActionID(category = "File", id = "linkagetest.mod3.TestAction")
@ActionRegistration(displayName = "#CTL_TEST")
@ActionReference(path = "Menu/File", position = 1300)
@Messages("CTL_TEST=TEST")
public final class TestAction implements ActionListener {

  @Override
  public void actionPerformed(ActionEvent e) {
    SP1 sp1 = Lookup.getDefault().lookup(SP1.class);
    SP2 sp2 = Lookup.getDefault().lookup(SP2.class);

    // and this is where the linkage fails
    sp2.doStuff(sp1.create());
  }
}

我得到:

java.lang.LinkageError: loader constraint violation: loader (instance of org/netbeans/StandardModule$OneModuleClassLoader) previously initiated loading for a different type with name "org/jdom2/Element"

我明白为什么org.jdom2.ElementModule1 和 Module2 中的类实例不一样,但是我应该如何设计这样的层次结构而不得到 LinkageError?我怎样才能传递对象?

4

1 回答 1

2

好的,我想通了。我必须仅通过一个模块提供库并将包声明为公共。

所以在pom.xml模块中Test-API我添加了公共包:

<plugins>
  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>nbm-maven-plugin</artifactId>
    <extensions>true</extensions>
    <configuration>
      <publicPackages>
        <publicPackage>linkagetest.api</publicPackage>
        <publicPackage>org.jdom2</publicPackage>
      </publicPackages>
    </configuration>
  </plugin>
  ...
于 2014-02-26T07:54:27.473 回答