How to find out what jar file provides a class during runtime using maven?

自古美人都是妖i 提交于 2020-01-29 21:19:40

问题


I run my application using mvn jetty:run

At compile time everything is fine, my row

  Tidy tidier = new Tidy();
    tidier.setInputEncoding("UTF-8");

compiles fine and the classpath shows the appropriate jar. However, at runtime I get the following exception and I cannot undestand why:

2009-11-11 17:48:53.384::WARN:  Error starting handlers
java.lang.NoSuchMethodError: org.w3c.tidy.Tidy.setInputEncoding(Ljava/lang/String;)V

I am now thinking maybe there are two different versions of this Tidy in my classpath (the one apparently is not named tidy, otherwise I could detect it in the classpath shown by maven). I am trying to find out what jar file it is and so far I have tried the following:

Class<?> tidyClass = Class.forName(Tidy.class.getName());
ClassLoader tidyLoader = tidyClass.getClassLoader();
String name = Tidy.class.getName() + ".class"; // results in tidyClass=class org.w3c.tidy.Tidy
System.out.println("resource="+tidyLoader.getResource(name)); // results in tidyLoader=org.codehaus.classworlds.RealmClassLoader@337d0f
System.out.println("path="+tidyLoader.getResource(name).getPath()); // results in resource=null

I read somewhere that the path should show the jar but apparently not with this classloader... how can I figure it out? Everything works like a charm in eclipse but when I run with maven I get this mess.. BTW eclipse says

tidyClass=class org.w3c.tidy.Tidy
tidyLoader=sun.misc.Launcher$AppClassLoader@1a7bf11
resource=null so no jar info either.

回答1:


try something like this:

    Class clazz = null;
    try {
        clazz = Class.forName( typeName );
        if ( clazz != null && clazz.getProtectionDomain() != null
                && clazz.getProtectionDomain().getCodeSource() != null )
        {
            URL codeLocation = clazz.getProtectionDomain().getCodeSource()
                    .getLocation();
            System.out.println( codeLocation.toString() );
        }
    }
    catch ( ClassNotFoundException e ) {
        System.out.println( e.getMessage() );
    }

where typeName="org.w3c.tidy.Tidy".



来源:https://stackoverflow.com/questions/1716290/how-to-find-out-what-jar-file-provides-a-class-during-runtime-using-maven

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!